以下代码如何运作?
var myNodeList = document.querySelectorAll('li'); // grabs some <li>
[].forEach.call(myNodeList, function (item) {
// :) hooray `item` can be used here
});
然而,
document.querySelectorAll('li').forEach.call(myNodeList, function (item) {
// throws error
});
阅读一些内容 - This accesses the created (empty) array’s prototype method and using call allows the NodeList to take advantage.
任何帮助都将不胜感激。
是什么让以下代码访问创建的(空)数组的原型方法并使用调用允许NodeList利用
[].forEach.call(myNodeList, function (item) {
// :) hooray `item` can be used here
});
https://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/
答案 0 :(得分:0)
document.querySelectorAll('li')
返回array like result申请foreach
您应该使用Array.apply
Array.apply(null, document.querySelectorAll('li')).forEach(function(item) {
console.log(item)
});