简体   繁体   English

为什么JavaScript不能将类似数组的对象转换为数组?

[英]Why does JavaScript not convert array-like objects to arrays?

While learning about DOM manipulation I noticed that Document methods such as getElementByTagName or querySelectorAll return HTMLCollection or NodeList objects which, however much they look like arrays, have to be converted to arrays using Arrays.from() if we want these collections to have the very useful array methods. 在学习DOM操作时,我注意到诸如getElementByTagName或querySelectorAll之类的Document方法返回HTMLCollection或NodeList对象,无论它们看起来如何像数组,如果我们希望这些集合具有非常好的数组,则必须使用Arrays.from()将其转换为数组。有用的数组方法。 I am wondering why this is so. 我想知道为什么会这样。 Is there any particular reason why JS does not automatically convert these collections to arrays? JS没有自动将这些集合转换为数组的特定原因吗?

Edit: It has been brought to my attention that NodeList has forEach() in all major browsers. 编辑:已经提请我注意NodeList在所有主要浏览器中都有 forEach()

The DOM collections have their own types, instead of being Array (or at least array subclass) instances, because they are very different from arrays. DOM集合具有自己的类型,而不是Array(或至少是数组子类)实例,因为它们与数组有很大的不同。 They are mere views on the DOM, they are not containers storing the elements themselves. 它们只是DOM上的视图 ,不是存储元素本身的容器。 They are immutable (ie you cannot .push() on them) or even live views (ie they always represent the selection in the current state of the document). 它们是不可变的(即您不能在它们上使用.push() )甚至是实时视图(即它们始终代表文档当前状态下的选择)。 Also they can only hold DOM nodes, you cannot put arbitrary values inside them like you can insert into arrays. 而且它们只能容纳DOM节点,不能像插入数组一样在其中放置任意值。

Sure, they are array-like in that they have indexed properties and a .length , but that's where the similarity ends. 当然,它们类似于数组,因为它们具有索引属性和.length ,但这就是相似性结束的地方。 Notice that it is only JavaScript that allows you to access the contents with index properties, according to the pure language-agnostic DOM you would use the .item(index) method. 注意,只有JavaScript才允许您使用索引属性访问内容,根据纯语言不可知DOM,您将使用.item(index)方法。 All this is why DOM collections got their own hierarchy and have nothing to do with the Array type that is built into JavaScript. 这就是为什么DOM集合具有自己的层次结构,而与JavaScript内置的Array类型无关。

You want the array-like DOM objects to be implicitly convertible to arrays. 您希望将类似数组的DOM对象隐式转换为数组。 Javascript is a very dynamic language and performs many such conversions automatically. JavaScript是一个非常动态的语言,并自动执行许多此类转换。 And it's one of the reasons this language is so hated in the community. 这也是该语言在社区中如此令人讨厌的原因之一。 For example: 1 == "1" returns true in Javascript. 例如: 1 == "1"在Javascript中返回true。

So the problem you posed is the age old problem of determining where should we draw the line. 因此,您提出的问题是确定我们应该在哪里划界的古老问题。

As you yourself pointed out, all you need to do is make a call to Arrays.from to get an actual array. 正如您自己指出的那样,您所需要做的就是调用Arrays.from以获取实际的数组。

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

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