NodeList.prototype.forEach = Array.prototype.forEach; [英] NodeList.prototype.forEach = Array.prototype.forEach;
问题描述
你看到以下任何问题:
NodeList.prototype.forEach = Array.prototype.forEach;
通常的forEach
只是一个阵列的性能,但将其设置为所有的属性节点列表
译文]好了,没有必要之前,你可以通过它的节点环路与的forEach
到节点列表
转换成数组。
Normally forEach
is just a property of arrays, but by setting it as a property of all NodeList
s as well, there's no need to convert a NodeList
to an array before you can loop through its nodes with forEach
.
推荐答案
这往往不是一个好主意,通过原型来扩展DOM的功能,尤其是在旧版本的IE(的文章)。
It's often not a good idea to extend the functionality of DOM through prototypes, especially in older versions of IE (article).
不过,你可以简单地使用 Array.prototype.forEach
即使不将其添加到原型链或将你的节点列表
到一个数组:
However, you can simply use Array.prototype.forEach
even without adding it to the prototype chain or converting your NodeList
into an array:
var list = document.querySelectorAll(".some.query");
Array.prototype.forEach.call(list, function(el){ /* ... */ });
/* or */
var forEach = function(ctn, callback){
return Array.prototype.forEach.call(ctn, callback);
}
forEach(list, function(el){ /* ... */ });
又见MDN:<一href=\"https://developer.mozilla.org/en-US/docs/DOM/NodeList#Why_can%27t_I_use_forEach_or_map_on_a_NodeList.3F\">Why我不能使用的forEach
或地图
在节点列表
。
这篇关于NodeList.prototype.forEach = Array.prototype.forEach;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!