5

1. What is a pseudo-array

There is a kind of array, or pseudo-array, in JavaScript. Artificial arrays are often seen function arguments objects, dom.querySelectorAll like acquired NodeList class ( NodeList itself forEach method) and the like.

Pseudo-array is not an array, it does not inherit Array.prototype , but it "looks like an array", it does not have standard methods for arrays, but it can reuse these standard methods.

example

function arrayLike() {
    arguments.forEach(a => console.log(a));//TypeError: arguments.forEach is not a function
}
arrayLike(1, 2, 3);

As shown in the above example, the arguments object itself does not have forEach methods, but it can reuse these standard methods of arrays.

example

function arrayLike() {
    // arguments.forEach(a => console.log(a));
    [].forEach.call(arguments, a => console.log(a));// 1 2 3 通过call改变this指向,调用数组的方法
    [...arguments].forEach(a => console.log(a));// 1 2 3  构建一个真实数组,然后调用数组的方法
}
arrayLike(1, 2, 3);

2. How to create a pseudo-array object

An array object must have two characteristics:

  1. Has an integer length attribute in the 0~2 32 -1
  2. The length property is greater than the maximum index of the object, the index is an integer in the range of 0-2 32 -2

So it is very simple, as long as these two characteristics are realized, an object is a pseudo-array object.

example

const arr = {
    1: 'AAA',
    3: 'CCC',
    length: 8,
};
[].forEach.call(arr, (item, i) => console.log(item, i)); //AAA 1 CCC 3

3. concat method of array

For arrays and pseudo-arrays, among the standard methods for arrays, only the concat method is not universal. For a pseudo-array, the concat method connects them as a whole.

example

console.log([].concat.call(arr, [7, 8]));//[ { '1': 'AAA', '3': 'CCC', length: 8 }, 7, 8 ]
console.log([1, 2].concat([7, 8]));//[ 1, 2, 7, 8 ]

concat for arrays and pseudo-arrays. When encountering this situation, we only have to convert the pseudo-arrays ourselves, for example:

1. Copy the pseudo-array through the slice method

console.log([].concat.call([].slice.call(arr), [7, 8]));
//[ <1 empty item>, 'AAA', <1 empty item>, 'CCC', <4 empty items>, 7, 8 ]

2. Symbol.isConcatSpreadable be pseudo array object change concat default behavior when operating

const arr = {
    1: 'AAA',
    3: 'CCC',
    length: 8,
    [Symbol.isConcatSpreadable]: true,
};
console.log([].concat.call(arr, [7, 8]));
//[ <1 empty item>, 'AAA', <1 empty item>, 'CCC', <4 empty items>, 7, 8 ]

forceddd
271 声望912 粉丝

一名前端爱好者。