Now that most browsers have implemented querySelectorAll, the native selectorEngine, many framework-dependent developers are getting a rude awakening when dealing with the result of QSA calls: the NodeList object. NodeLists are array-like but don't feature many of the methods provided by the Array, like forEach
, map
, filter
, etc. JavaScript does, however, provide a very simple way to convert NodeLists to Arrays:
现在,大多数浏览器已经实现了querySelectorAll,本机的选择器引擎,许多依赖于框架的开发人员在处理QSA调用的结果(NodeList对象)时都变得无礼。 NodeLists类似于数组,但是没有Array提供的许多方法,例如forEach
, map
, filter
等。但是,JavaScript确实提供了一种非常简单的方法将NodeLists转换为Arrays:
var nodesArray = Array.prototype.slice.call(document.querySelectorAll("div"));
The result of the code above is a true Array object containing all of the nodes returned by the QSA. You could even make the code shorter with this alternative:
上面代码的结果是一个真实的Array对象,其中包含QSA返回的所有节点。 您甚至可以使用以下替代方法使代码更短:
var nodesArray = [].slice.call(document.querySelectorAll("div"));
Both snippets will give you an Array for which you can iterate over and do all those other awesome array things!
这两个代码片段都将为您提供一个数组,您可以对其进行迭代并执行所有其他出色的数组操作!