在 ES6 中过滤或映射节点列表 [英] Filter or map nodelists in ES6

查看:26
本文介绍了在 ES6 中过滤或映射节点列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ES6 中过滤或映射节点列表的最有效方法是什么?

What is the most efficient way to filter or map a nodelist in ES6?

根据我的阅读,我会使用以下选项之一:

Based on my readings, I would use one of the following options:

[...nodelist].filter

Array.from(nodelist).filter

你会推荐哪一个?有没有更好的方法,例如不涉及数组?

Which one would you recommend? And are there better ways, for example without involving arrays?

推荐答案

  • [...nodelist] 如果对象是可迭代的,则会从对象中创建一个数组.
  • Array.from(nodelist) 如果对象是可迭代的或者,如果对象是类似数组的(具有 .长度和数字道具)
    • [...nodelist] will make an array of out of an object if the object is iterable.
    • Array.from(nodelist) will make an array out of an object if the object is iterable or if the object is array-like (has .length and numeric props)
    • 如果 NodeList.prototype[Symbol.iterator] 存在,您的两个示例将是相同的,因为这两种情况都包含可迭代对象.如果您的环境尚未配置为 NodeList 是可迭代的,那么您的第一个示例将失败,而第二个示例将成功.Babel 目前不能正确处理这种情况.

      Your two examples will be identical if NodeList.prototype[Symbol.iterator] exists, because both cases cover iterables. If your environment has not been configured such that NodeList is iterable however, your first example will fail, and the second will succeed. Babel currently does not handle this case properly.

      因此,如果您的 NodeList 是可迭代的,则完全取决于您使用哪个.我可能会根据具体情况进行选择.Array.from 的一个好处是它接受映射函数的第二个参数,而第一个 [...iterable].map(item => item)必须创建一个临时数组,Array.from(iterable, item => item) 不会.但是,如果您没有映射列表,则没有关系.

      So if your NodeList is iterable, it is really up to you which you use. I would likely choose on a case-by-case basis. One benefit of Array.from is that it takes a second argument of a mapping function, whereas the first [...iterable].map(item => item) would have to create a temporary array, Array.from(iterable, item => item) would not. If you are not mapping the list however, it does not matter.

      这篇关于在 ES6 中过滤或映射节点列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆