Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

javascript - Filter or map nodelists in 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

or

Array.from(nodelist).filter

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • [...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)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...