问题描述
在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)
将从对象中组成数组;如果对象是类似数组的对象(具有.length
和数字属性),则 [...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中过滤或映射节点列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!