迭代DOM节点列表时的.call行为

时间:2016-06-07 06:10:06

标签: javascript

以下代码如何运作?

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/

1 个答案:

答案 0 :(得分:0)

document.querySelectorAll('li')返回array like result申请foreach您应该使用Array.apply

Array.apply(null, document.querySelectorAll('li')).forEach(function(item) {
    console.log(item)
  });

fiddle

相关问题