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

后端 未结 1 1550
借酒劲吻你
借酒劲吻你 2021-02-05 19:48

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. So much so that

相关标签:
1条回答
  • 2021-02-05 19:56

    Well, speaking about core Javascript objects, the arguments is a good example to talk about.

    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.

    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.

    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.

    NodeLists generally are live objects, their structure is reflects any change on the underlying DOM structure...

    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.

    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:

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

    See also:

    • Why isn't a function's arguments object an array in Javascript?
    0 讨论(0)
提交回复
热议问题