为什么没有数据? [英] Why doesn't nodelist have forEach?

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

问题描述

我正在使用一个简短的脚本来更改< abbr> 元素的内部文本,但发现 nodelist 没有一个 forEach 方法。我知道 nodelist 不继承 Array ,但它似乎不像 forEach 会有一个有用的方法吗?是否有一个特定的实现问题我不知道这阻止了将 forEach 添加到 nodelist

I was working on a short script to change <abbr> elements' inner text, but found that nodelist does not have a forEach method. I know that nodelist doesn't inherit from Array, but doesn't it seem like forEach would be a useful method to have? Is there a particular implementation issue I am not aware of that prevents adding forEach to nodelist?

注意:我知道Dojo和jQuery对于他们的nodelists都有某种形式的 forEach

Note: I am aware that Dojo and jQuery both have forEach in some form for their nodelists. I cannot use either due to limitations.

推荐答案

这些答案都不解释为什么 NodeList不继承自Array,因此允许它具有 forEach ,而其余所有。

None of these answers explain why NodeList doesn't inherit from Array, thus allowing it to have forEach and all the rest.

答案发现在这个es讨论的线程上 。简而言之,它打破了网络:

The answer is found on this es-discuss thread. In short, it breaks the web:


该问题是错误地假定instanceof的代码,意思是实例是与Array结合的数组.prototype.concat。

The problem was code that incorrectly assumed instanceof to mean that the instance was an Array in combination with Array.prototype.concat.

Google的Closure Library中有一个错误,导致几乎所有Google的应用程序都因此失败。图书馆一经发现就被更新,但仍然可能会出现代码,这些错误的假设与concat相结合。

There was a bug in Google's Closure Library which caused almost all Google's apps to fail due to this. The library was updated as soon as this was found but there might still be code out there that makes the same incorrect assumption in combination with concat.

也就是说,一些代码做了一些类似

That is, some code did something like

if (x instanceof Array) {
  otherArray.concat(x);
} else {
  doSomethingElseWith(x);
}

但是, concat 将处理与其他对象不同的真实数组(而不是instanceof数组):

However, concat will treat "real" arrays (not instanceof Array) differently from other objects:

[1, 2, 3].concat([4, 5, 6]) // [1, 2, 3, 4, 5, 6]
[1, 2, 3].concat(4) // [1, 2, 3, 4]

所以这意味着上述代码在 x 是一个NodeList,因为在它下降 doSomethingElseWith(x)路径之前,而之后它下降了$ code otherArray.concat(x) / code>路径,这样做有些奇怪,因为 x 不是一个真正的数组。

so that means that the above code broke when x was a NodeList, because before it went down the doSomethingElseWith(x) path, whereas afterward it went down the otherArray.concat(x) path, which did something weird since x wasn't a real array.

有一段时间,有一个提议是一个元素类,它是Array的一个真正的子类,并将被用作新的NodeList。但是,这是从DOM标准中删除,至少现在,因为它是'对于各种技术和规格相关的原因,t可以实施。

For some time there was a proposal for an Elements class that was a real subclass of Array, and would be used as "the new NodeList". However, that was removed from the DOM Standard, at least for now, since it wasn't feasible to implement yet for a variety of technical and specification-related reasons.

这篇关于为什么没有数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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