迭代 DOM 节点列表上的调用行为



以下代码如何工作?

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/

document.querySelectorAll('li')返回类似数组的结果以应用foreach您应该使用 Array.apply

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

小提琴

最新更新