类数组
什么是类数组?
类数组对象 (Array-like Object) 是类似数组一样有length属性和索引属性的对象。例如:
const arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 }
类数组这个概念有什么用?
因为类数组对象不是数组,为了按数组的方式处理,可以把类数组转换成真正的数组后使用。例如,使用Array.prototype.map()方法 或 作为apply()的参数。
类数组对象转换数组的方式
const arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 };
console.log(arrayLike);
//{ '0': 'a', '1': 'b', '2': 'c', length: 3 }
// ES5 写法一
const array1 = [].slice.call(arrayLike);
console.log(array1);
//[ 'a', 'b', 'c' ]
// ES5 写法二
const array2 = Array.prototype.slice.call(arrayLike);
console.log(array2);
//[ 'a', 'b', 'c' ]
// ES6
const array3 = Array.from(arrayLike);
console.log(array3);
//[ 'a', 'b', 'c' ]
常见的类数组
1. arguments
console.log(Array.isArray(arguments));
//false
console.log(arguments);
//node打印: {}
//chrome打印: Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ]
//因为arguments具有Symbol.iterator属性,所以它可以用扩展运算符(...arguments) 或 其他使用迭代器的方法
2. NodeList
//仅限浏览器中
const nodeList = document.querySelectorAll('*');
console.log(Array.isArray(nodeList));
//false
3. 字符串 String
const array = Array.from('abc');
console.log(array);
//["a", "b", "c"]
4. TypedArray
const typedArray = new Int8Array(new ArrayBuffer(3));
console.log(Array.isArray(typedArray));
//false
…待补充
其他
另外, {length:0} 是类数组的特殊情况,转换时可以执行成功,返回空数组[]。
console.log(Array.from({length:0}));
//[]
console.log(Array.from(''));
//[]