Home >Web Front-end >JS Tutorial >Array.prototype.concat is not a universal method to refute [Translation]_javascript skills

Array.prototype.concat is not a universal method to refute [Translation]_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:49:541265browse

ECMAScript 5.1 Specification§15.4.4.4 says:

Copy code The code is as follows:

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:

Copy code The code is as follows:

> ["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.
Copy Code The code is as follows:

> [].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:

Copy code The code is as follows:

> function f() { return [].concat .call(arguments, ["world"]) }
> f("hello")
[ { '0': 'hello' }, 'world' ]


The real universal method should be like this Array.prototype.push:
Copy the code The code is as follows:

> 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.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn