1. What is a pseudo array
There is a kind of array, or pseudo array, in JavaScript. Often seen pseudo arrays have functionsarguments
Objectdom.querySelectorAll
EtcNodeList
Class(NodeList
OwnforEach
Method), etc.
A pseudo array is not an array, it does not inheritArray.prototype
However, it “looks like an array”. It has no 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,arguments
The object itself does notforEach
Method, 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 change the point of this through call and call the method of array
[...arguments]. forEach(a => console.log(a));// 123 build a real array and call the array method
}
arrayLike(1, 2, 3);
2. How to create a pseudo array object
An array object must have two characteristics:
- Has a range in0~232-1Integer length property of
- The length attribute is greater than the maximum index of the object, which is a0-232 -2Integer in range
So it’s very simple. As long as these two features are implemented, 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. Of arrayconcat
method
For arrays and pseudo arrays, in the standard method of arrays, onlyconcat
Methods are not universal. For a pseudo array,concat
Method connects it 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 ]
The above example shows array and pseudo array callsconcat
In this case, we have to convert the pseudo array ourselves, for example:
1. Copy the pseudo array through 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. AdoptionSymbol.isConcatSpreadable
Change to pseudo array objectconcat
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 ]