- 伪数组
一种相似数组的对象,它们不具备数组的规范办法,然而作为可迭代对象能够对它们像数组一样进行迭代,常见的伪数组对象:
- NodeList(dom.querySelectorAll等获取)
- Arguments对象
- FileList对象
- String对象
const foo = (a,b,c) => arguments;const args = foo(1,2,3,4);for(let item of args) { console.log(item);}// 1// 2// 3// 4// 测验arguemnts对象类型args instanceof Object; // trueObject.prototype.toString.call(args); // "[object Arguments]"
- 手动创立伪数组对象
const arrayLike = { 1: "AAA", 3: "CCC", 5: "BBB", length: 6};// 复用数组办法[].forEach.call(arr, (item, i) => console.log(item, i)); // AAA 1 // CCC 3 // BBB 5
对于数组和伪数组,在数组的规范办法中,只有concat办法是不通用的
console.log([].concat.call(arr, [7, 8])); // [ { '1': 'AAA', '3': 'CCC', 5: "BBB", length: 6 }, 7, 8 ]console.log([1, 2].concat([7, 8])); // [ 1, 2, 7, 8 ]// 解决方案1. slice[].concat.call([].slice.call(arr), [7, 8]); 2. Symbol.isConcatSpreadablearr[Symbol.isConcatSpreadable] = true;[].concat.call(arr, [7, 8]);// [empty, "AAA", empty, "CCC", empty, "BBB", 7, 8]
- 伪数组对象和数组的转换
- Array.from
- 扩大运算符
- Object.entries
console.log(Array.from(args)); // [1,2,3,4]console.log([...args]); // [1,2,3,4]console.log(Object.entries(args).map(([,val]) => val)); // [1,2,3,4]