简体   繁体   English

为什么在Javascript中使用类似于数组的对象而不是本机数组

[英]Why Are Array-Like Objects Used in Javascript Over Native Arrays

It's very common in Javascript to come across Array-Like objects with some similarities to the build in Array type but without all of its methods or features. 在Javascript中很常见的是类似于Array的对象,它与Array类型的构建有一些相似之处,但没有它的所有方法或功能。 So much so that there are some tricks to convert Array-Like objects to "real" arrays for further manipulation. 因此,有一些技巧可以将类似Array的对象转换为“真正的”数组,以便进一步操作。

This is even mentioned in Javascript: The Definitive Guide . Javascript:The Definitive Guide中甚至提到了这一点。

The questions is why is this pattern so common? 问题是为什么这种模式如此常见? Why not prefer the built-in Array type in all these cases? 在所有这些情况下,为什么不更喜欢内置的Array类型呢?

Well, speaking about core Javascript objects, the arguments is a good example to talk about. 好吧,谈到核心 Javascript对象, arguments是一个很好的例子。

In this case it has been an array-like object since the beginning, appeared in the ECMAScript 1th Edition Specification already as a simple object. 在这种情况下,它从一开始就是一个类似于数组的对象 ,已经作为一个简单的对象出现在ECMAScript第1版规范中。

Why? 为什么? I think at that time there were only four built-in Array methods, and maybe the designer didn't think it worthed too much, later the change was proposed, but Microsoft (part of the TC39 committee) didn't approved the change, the fear of breaking the web has always been present. 我认为当时只有四种内置Array方法,也许设计师并不认为它过多,后来提出了改变,但微软(TC39委员会的一部分)没有批准这一改变, 打破网络的恐惧一直存在。

Now going to host objects , the DOM, NodeLists come to my mind, I think they didn't wanted to use the native Array type due the dynamic behavior of these objects. 我现在想要托管对象 ,DOM, NodeLists ,我认为由于这些对象的动态行为,他们不想使用本机Array类型。

NodeLists generally are live objects, their structure is reflects any change on the underlying DOM structure... NodeLists通常是活动对象,它们的结构反映了底层DOM结构的任何变化......

Personally I like array-objects, because they are really lightweight, before ECMAScript 5, there were a lot of restrictions in core methods, regarding the usage of user-defined array-like objects. 我个人喜欢数组对象,因为它们非常轻量级,在ECMAScript 5之前,核心方法有很多限制,关于用户定义的类数组对象的使用。

For example, the apply method of function objects, in ECMAScript <= 3, allowed only either a real array or an arguments object as its second argument, now in ES5, the following is possible: 例如,在ECMAScript <= 3中,函数对象的apply方法只允许实数数组或参数对象作为其第二个参数,现在在ES5中,以下是可能的:

var arrayLike = {0: 'hello ', 1:'world', length:2};
(function (a,b) { alert(a+b); }).apply(null, arrayLike);

See also: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM