HTMLCollection是一个数组吗? [英] Is HTMLCollection An Array?

查看:1131
本文介绍了HTMLCollection是一个数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道HTMLCollection实际上不是一个数组,否则它将被定义为一个数组。我使用一个帮助函数,我调用isArray()来检测一个对象是否是一个数组。我在这个地方使用这个小助手,并且在检查htmlCollection时,我一直在运行这个返回false的问题。

  var isArray:function(obj){
var type = Function.prototype.call.bind(Object.prototype .toString);
返回类型(obj)==='[object Array]'|| type(obj)==='[object HTMLCollection]';

在这个帮助函数中检查htmlCollection类型并假设是错误的它和数组是一样的吗?是什么使它有所不同?除了它的HTML元素,而不是javascript对象。

解决方案

不,它是 HTMLCollection ,而不是 Array

它具有类似数组的特性,如数字属性和 .length 属性,但它不会继承从 Array.prototype 。因此它没有标准的 Array 方法,所以应该被看作是不同的。



另一个显着的差异是 HTMLCollection 是一个live集合,这意味着它随着DOM更新而更新。如果您从DOM中删除其中的一个节点,它将自动从 HTMLCollection 中移除。


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.

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.

解决方案

No, it's an HTMLCollection, not an 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.

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是一个数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆