//如果判断Array类型
var arr = [];
arr instanceof Array; //true
Array.isArray(arr); //true
Object.prototype.toString.call(arr).slice(8,-1); //"Array"
Array.from 和 [...] 都可以将类数组转为数组
Array.from 只要有索引和长度
[...]则必须可以被迭代
var obj = { 0: 1, 1: 2, 2: 3, length: 3 };
Array.from(obj); //[1,2,3]
[...obj]; //Uncaught TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
var obj = {
0: 1,
1: 2,
2: 3,
length: 3,
[Symbol.iterator]: function* () {
var index = 0;
while (index < this.length) {
yield this[index++];
}
},
};
Array.from(obj); //[1,2,3]
[...obj]; //[1,2,3]
网友评论