javascript HTMLCollection 是一个数组吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12770147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is HTMLCollection An Array?
提问by ryandlf
I understand that HTMLCollection is not actually an array, or else it would be defined as an array. I use a help function that I call isArray() to detect whether or not an object is an array. I use this little helper all over the place and i've been running problems on this returning false when checking against an htmlCollection.
我知道 HTMLCollection 实际上不是一个数组,否则它会被定义为一个数组。我使用调用 isArray() 的帮助函数来检测对象是否为数组。我到处都使用这个小助手,并且在检查 htmlCollection 时,我一直在运行这个返回 false 的问题。
var isArray: function(obj) {
var type = Function.prototype.call.bind( Object.prototype.toString );
return type(obj) === '[object Array]' || type(obj) === '[object HTMLCollection]';
}
Would it be wrong to check for the htmlCollection type within this helper function and assume that it is the same thing as an array? What makes it any different? Other than its html elements as opposed to javascript objects.
检查此辅助函数中的 htmlCollection 类型并假设它与数组相同是否是错误的?是什么让它与众不同?除了它的 html 元素而不是 javascript 对象。
回答by I Hate Lazy
No, it's an HTMLCollection
, not an Array
.
不,它是一个HTMLCollection
,而不是一个Array
。
It has Array-like characteristics, like numeric properties, and a .length
property, but it does not inherit from Array.prototype
. Therefore it does not have the standard Array
methods, and so should be seen as being different.
它具有类似数组的特性,如数字属性和一个.length
属性,但它不继承自Array.prototype
. 因此它没有标准的Array
方法,因此应该被视为不同的。
Another significant difference is that HTMLCollection
is a "live" collection, which means that it updates as the DOM updates. If you remove one of its nodes from the DOM, it will be removed from the HTMLCollection
automatically.
另一个显着区别是它HTMLCollection
是一个“实时”集合,这意味着它会随着 DOM 更新而更新。如果您从 DOM 中删除其节点之一,它将HTMLCollection
自动从 DOM 中删除。
回答by rdonatoiop
If you are considering an Array conversion, please refer to this post:
如果您正在考虑数组转换,请参考这篇文章:
Most efficient way to convert an HTMLCollection to an Array.
将 HTMLCollection 转换为 Array 的最有效方法。
They discussed some methods, and the solution in the selected answer also worked in a situation I′ve experienced.
他们讨论了一些方法,所选答案中的解决方案也适用于我遇到的情况。