NodeList.prototype.forEach = Array.prototype.forEach; 节点列表的forEach方法将被设置为数组的forEach方法。

18
你看到以下代码有什么问题吗?
NodeList.prototype.forEach = Array.prototype.forEach;

通常情况下,forEach 只是数组的一个属性,但是将其设置为所有 NodeList 的属性后,无需在使用 forEach 循环节点之前将 NodeList 转换为数组。请注意保留 HTML 标签。

我喜欢这个想法。等待其他人指出其中的任何问题。 - Salman
请查看NodeList.js - Edwin Reynoso
4个回答

7
通常不建议通过原型扩展DOM的功能,特别是在较旧的IE版本中(参见文章)。
然而,您可以简单地使用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){ /* ... */ });

参见 MDN:为什么不能在 NodeList 上使用 forEachmap


如果不是因为旧版本的IE,JS的许多功能本来可以完美地运行。 - Alnitak
你为什么要使用 Array.prototype.forEach.call(...,而不是只使用 Array.prototype.forEach(...,因为在MDN的语法中说第二个参数可以定义 this。我只是想提高我的理解水平。 - Muhammad Umer
@MuhammadUmer:请不要在评论中提问。如果我在StackOverflow上不再活跃,你将永远得不到答案。话虽如此,thisArg是在callback期间的this值,而不是在Array.prototype.forEach期间的。 - Zeta
谢谢您抽出时间回答问题...如果您想要进一步解释,请随意。http://stackoverflow.com/questions/25801934/what-is-a-difference-between-array-prototype-foreach-call-vs-array-prototype-for - Muhammad Umer
很不幸,这种方法对于XML文档的节点并没有起作用,即通过XMLHttpRequest或使用jQuery $.get("/test.xml", function(xmlDocument) { Array.prototype.forEach.call(xmlDocument.childNodes, function(node) {...}); });检索到的节点。然而,此帖子中的解决方案效果很好:Array.from(xmlDocument.childNodes).forEach(function(node) {...});。对于DOM文档的节点,它也能正常工作:NodeList.prototype.forEach = Array.prototype.forEach; document.childNodes.forEach(function(node) { ... });。FF v45,Chrome v53。 - dma_k

2
如果您正在开发一个其他人会使用的库,这样做可能不是个好主意。如果只是自己的代码(例如网站),那应该没什么问题。不过最好还是加上保护措施,因为将来浏览器将原生支持 NodeList.prototype.forEach(Chrome 已经支持了)。
if (!NodeList.prototype.forEach) {
  NodeList.prototype.forEach = Array.prototype.forEach;
}

0

0
如 Zeta 所提到的,最好使用一个便利函数。然而,这个版本将允许您给它上下文。
var forEach = function(list, callback, context){
  return Array.prototype.forEach.call(list, callback, context);
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接