将NodeList转换为数组

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提供的许多方法,例如forEachmapfilter等。但是,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!

这两个代码片段都将为您提供一个数组,您可以对其进行迭代并执行所有其他出色的数组操作!

翻译自: https://davidwalsh.name/nodelist-array

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值