你看到的任何问题,以下内容:NodeList.prototype.forEach = Array.prototype.forEach;
NodeList.prototype.forEach = Array.prototype.forEach;
通常forEach
仅仅是一个阵列的性能,但通过将其设定为所有NodeList
S以及财产,没有必要到NodeList
转换为数组之前,您可以循环通过其节点forEach
。
你看到的任何问题,以下内容:NodeList.prototype.forEach = Array.prototype.forEach;
NodeList.prototype.forEach = Array.prototype.forEach;
通常forEach
仅仅是一个阵列的性能,但通过将其设定为所有NodeList
S以及财产,没有必要到NodeList
转换为数组之前,您可以循环通过其节点forEach
。
通过原型扩展DOM的功能通常不是一个好主意,特别是在旧版本的IE(article)中。
但是,你可以简单地使用Array.prototype.forEach
即使不将其添加到原型链或将您的NodeList
到一个数组:
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){ /* ... */ });
有很多JS的功能,如果它不适用于旧版本的IE,它可以很好地工作。 – Alnitak 2013-03-07 09:41:53
为什么你使用'Array.prototype.forEach.call('...而不是只是'Array.prototype.forEach(...)在MDN语法中它说你可以在第二个参数中定义'this'.HTTP ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach我只是想提高我的理解力。 – 2014-09-12 03:47:45
@MuhammadUmer:请不要在评论中提问。我没有在StackOverflow上活跃,你永远不会得到答案。也就是说,'thisArg'是'callback'过程中'this'的值,'Array.prototype.forEach'过程中__not__。 – Zeta 2014-09-12 05:49:07
正如Zeta所说,使用便利功能会更好。然而,这个版本将允许你给它上下文。
var forEach = function(list, callback, context){
return Array.prototype.forEach.call(list, callback, context);
};
如果您正在研究一个将被其他人使用的库,那么这样做并不是一个好主意。
如果它只是你自己的代码(即一个网站),那么我想这没什么大不了的。你应该保护它,因为在未来,浏览器本地支持NodeList.prototype.forEach
(Chrome已经)。
if (!NodeList.prototype.forEach) {
NodeList.prototype.forEach = Array.prototype.forEach;
}
我喜欢这个想法..等待别人指出其中的任何问题。 – 2013-03-07 09:28:17
查看[NodeList.js](https://github.com/eorroe/NodeList.js) – 2015-08-08 13:52:27