var doms = documents.querySelectorAll('span');
for(var i = 0; i < doms.length; i++){
var element = doms[i];
}
Array.prototype.forEach.call(doms,function(element){
// Do something with DOM
})
[].foreach.call(doms,function(element){
// Do something with DOM
})
NodeList.prototype.forEach = Array.prototype.forEach;
doms.foreach(function (element){
// Do something with DOM
})
4. 原生 Nodelist forEach 函数
2016 年以后版本的浏览器 Can I use Global -> 89.72%
MDN - NodeList.prototype.forEach()
语法:NodeList.forEach(callback[, thisArg]);
doms.forEach(function(currentValue,currentIndex,listObj){
// Do something with DOM
// currentValue: 当前循环的元素
// currentIndex:当前序号
// listObj:应用 forEach 的 NodeList 元素
// thisArg:执行回调时,使用 `this` 可以获取到的值
},
'myThisAry'
)
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = function (callback, thisArg) {
thisArg = thisArg || window;
for (var i = 0; i < this.length; i++) {
callback.call(thisArg, this[i], i, this);
}
};
}
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = Array.prototype.forEach;
}