ECMAScript 5.1 Specification§15.4.4.4 It says:
Copy the codeThe code is as follows:
The concat function is intentionally designed to be general; it does not require that its this value must be an Array object. Therefore, it can be transferred to other types of objects to be called as a method.
The code in this article uses [] as a shortcut. This is a common trick, although the readability is slightly less readable: you access the above method through an object instance. However, this access method is so fast in modern JavaScript engines that I suspect that in this way, these JavaScript engines may no longer create array instances. All the examples in this article have been tried to run in Firefox and V8.
Let's see if concat is a general method: If it is a general method, regardless of whether this value is a real array or an array object of class (has a length attribute and can access each element through the index), the method's return result should be the same. First, we try to call the concat method on the array:
Copy the codeThe code is as follows:
> ["hello"].concat(["world"])
["hello", "world"]
> [].(["hello"], ["world"]) // Same as above
["hello", "world"]
Then, we use an array object of class to perform the join operation above. The result should be the same.
Copy the codeThe code is as follows:
> [].({ 0: "hello", length: 1 }, ["world"])
[ { '0': 'hello', length: 1 }, 'world' ]
The special variable arguments are also an array object of the class. The result is still not what we expect:
Copy the codeThe code is as follows:
> function f() { return [].(arguments, ["world"]) }
> f("hello")
[ { '0': 'hello' }, 'world' ]
The real general approach should be like this:
Copy the codeThe code is as follows:
> var arrayLike = { 0: "hello", length: 1 };
> [].(arrayLike, "world")
2
> arrayLike
{ '0': 'hello', '1': 'world', length: 2 }
Translator's note: The browser is only implemented according to the standards, so there is no bug problem.