NodeList.prototype.forEach = Array.prototype.forEach; [英] NodeList.prototype.forEach = Array.prototype.forEach;

查看:268
本文介绍了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 NodeLists 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屋!

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