在第一个结果处停止的JavaScript过滤器 [英] JavaScript filter that stops at the first result
问题描述
JavaScript中是否有一种类似于filter
的机制(无需自己编写).但是,它不会返回集合中所有已过滤的元素,而只会返回第一个.当然,我可以执行以下操作以获得第一个偶数:
Is there a mechanism in JavaScript (without having to write my own) similar to filter
. Instead of returning all the filtered elements of a collection though, it only returns the first one. Of course I could do the following to get the first even number:
[7,5,3,2,1].filter(x => x % 2 == 0)[0]
但是,如果该列表中还有1000万个数字,那么将会有很多不必要的工作.在Haskell这样的语言中,由于懒惰的评估,因此不会查看其他1000万个数字.
But if there were 10 million more numbers in that list, there'd be a lot of unnecessary work. In a language like Haskell, the other 10 million numbers wouldn't be looked at due to lazy evaluation.
JavaScript中是否有一种机制可以执行上述操作,而不会在第一个结果之后评估任何元素?
Is there a mechanism in JavaScript to do the above without evaluating any elements after the first result?
推荐答案
您可以尝试从文档中
find()方法返回数组中第一个元素的值 满足提供的测试功能.否则未定义是 返回.
The find() method returns a value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
简单基准测试
var arr = [...Array(10000)].map( (item, idx) => idx )
arr.filter(i => i == 3000)[0]
arr.find(i => i == 3000)
/*
arr.filter x 1,358 ops/sec ±0.40% (91 runs sampled)
arr.find x 23,743 ops/sec ±0.40% (90 runs sampled)
Fastest is arr.find
*/
这篇关于在第一个结果处停止的JavaScript过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!