Heim  >  Artikel  >  Web-Frontend  >  Array.prototype.concat不是通用方法反驳[译]_javascript技巧

Array.prototype.concat不是通用方法反驳[译]_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:49:541204Durchsuche

ECMAScript 5.1规范§15.4.4.4 中说到:

复制代码 代码如下:

concat函数是有意设计成通用的;它并不要求它的this值必须得是个Array对象.因此,它可以被转移到其它类型的对象上作为方法来调用.


本文中的代码都使用了[]来作为Array.prototype的快捷方式.这已经是很常用的技巧了,虽然可读性差点:你通过一个对象实例访问到了Array.prototype上的方法.但是,这样的访问方式在现代的JavaScript引擎中非常之快,以至于我怀疑,说不定在这种调用方式下,这些JavaScript引擎可能已经不再创建数组实例了.本文中所有的例子都在Firefox和V8中尝试运行过.

让我们看一下concat到底是不是个通用方法:如果它是一个通用方法,则不管this的值是一个真实数组还是个类数组对象(拥有length属性,能通过索引访问每个元素),方法的返回结果都应该是一样的.我们首先尝试在数组上调用concat方法:

复制代码 代码如下:

> ["hello"].concat(["world"])
["hello", "world"]

> [].concat.call(["hello"], ["world"]) // 和上面的一样
["hello", "world"]


然后,我们使用一个类数组对象来进行上面的连接操作.结果应该是一样的.
复制代码 代码如下:

> [].concat.call({ 0: "hello", length: 1 }, ["world"])
[ { '0': 'hello', length: 1 }, 'world' ]

特殊变量arguments也是一个类数组对象.结果仍然不是我们所期望的:

复制代码 代码如下:

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


真正的通用方法应该是这样的Array.prototype.push:
复制代码 代码如下:

> var arrayLike = { 0: "hello", length: 1 };
> [].push.call(arrayLike, "world")
2
> arrayLike
{ '0': 'hello', '1': 'world', length: 2 }


译者注:浏览器只是按照标准来实现,所以并不存在bug的问题.
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn