JavaScript 中是否有类似filter
的机制(无需自己编写)。但是,它不会返回集合的所有过滤元素,而是只返回第一个元素。当然,我可以执行以下操作以获得第一个偶数:
[7,5,3,2,1].filter(x => x % 2 == 0)[0]
但如果该列表中有 1000 万个数字,就会有很多不必要的工作。在像 Haskell 这样的语言中,由于延迟计算,其他 1000 万个数字不会被查看。
JavaScript 中是否有一种机制可以在第一个结果之后不评估任何元素的情况下执行上述操作?
最佳答案
你可以试试.find
:
[7,5,3,2,1].find(x => x % 2 == 0);
// result: 2
来自docs :
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 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41754839/