ECMAScript 5.1 Specification§15.4.4.4 says:
The concat function is intentionally designed to be universal; it does not require that its this value must be an Array object. Therefore, it can be transferred to other types of objects and called as a method.
The code in this article all uses [] as a shortcut to Array.prototype. This is already a very common technique, although it is less readable: you access it through an object instance Method on Array.prototype. However, this access method is so fast in modern JavaScript engines that I suspect that these JavaScript engines may no longer create array instances in this calling method. This article All the examples in have been tried in Firefox and V8.
Let's take a look at whether concat is a universal method: if it is a universal method, it does not matter whether the value of this is a real array or a For array-like objects (which have a length attribute and can access each element by index), the return result of the method should be the same. We first try to call the concat method on the array:
> ["hello"].concat(["world"])
["hello ", "world"]
> [].concat.call(["hello"], ["world"]) // Same as above
["hello", "world" ]
Then, we use an array-like object to perform the above connection operation. The result should be the same.
> [].concat.call({ 0: "hello", length: 1 }, ["world"])
[ { '0': 'hello', length: 1 }, 'world' ]
The special variable arguments is also an array-like object. The result is still not what we expected:
> function f() { return [].concat .call(arguments, ["world"]) }
> f("hello")
[ { '0': 'hello' }, 'world' ]
The real universal method should be like this Array.prototype.push:
> var arrayLike = { 0: "hello", length: 1 };
> [].push.call(arrayLike, "world")
2
> arrayLike
{ '0': 'hello', '1': 'world', length: 2 }
Translator's Note: The browser only implements it according to the standard, so it does not There is no bug problem.