1. What is a pseudo-array
There is a kind of array, or pseudo-array, in JavaScript. Common pseudo-arrays include function arguments objects, dom.querySelectorAll, NodeList class (NodeList itself has forEach methods), etc.
A pseudo-array is not an Array, it doesn’t inherit array. prototype, but it “looks like an Array”. It doesn’t have standard methods for arrays, but it can reuse them.
example
function arrayLike() {
arguments.forEach(a= > console.log(a));//TypeError: arguments.forEach is not a function
}
arrayLike(1.2.3);
Copy the code
As shown in the example above, 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 change this pointer by calling the array method
[...arguments].forEach(a= > console.log(a));// 1, 2, 3 build a real array and call the array method
}
arrayLike(1.2.3);
Copy the code
2. How to create a pseudo-array object
An array object must have two characteristics:
- Has a range in
0~2<sup>32</sup>-1
Length property of the integer type - The length attribute is greater than the object’s maximum index, which is one
0-2<sup>32</sup> -2
Integers in the range
So it’s very simple, once you implement these two characteristics, 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
Copy the code
(3) of the arrayconcat
methods
For arrays and pseudo-arrays, only the concat method is not generic among the standard methods for arrays, concatenating a pseudo-array 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]
Copy the code
The above example shows the different results of concat calls to arrays and pseudo-arrays. In this case, we have to convert the pseudo-array ourselves, for example:
1. Copy the pseudo-array using 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 ]
Copy the code
2. Through the Symbol. IsConcatSpreadable change to concat pseudo array object when the default behavior of the operation
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 ]
Copy the code