javascript 上的 find() 和 filter().shift() 之间的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33759109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between find() and filter().shift() on javascript
提问by neiker
I recently starting to drop underscore/lodash overuse on (some of) my projects and realize that there's no full support of findmethod in browsers. What's the difference between ES6 method findand using .shift() over filterresults
我最近开始在我的(一些)项目中放弃过度使用下划线/lodash,并意识到浏览器中没有完全支持find方法。ES6 方法find和使用 .shift()过滤结果有什么区别
var user = users.find(function() { ... } );
or
或者
var user = users.filter(function() { ... } ).shift();
I imagine there's obvious optimization over "find" method (stop iterating on fist match), but can I get unexpected results using second approach? Should I use the polyfillinstead? Why?
我想对“find”方法有明显的优化(停止迭代拳头匹配),但是我可以使用第二种方法得到意想不到的结果吗?我应该改用polyfill吗?为什么?
回答by Bergi
Apart from the obvious (and noticeable) overhead, yes, the results might vary. filter
runs till the end of the array, and invokes its callback on every item; in contrast to find
which stops after having found one. When the callback throws an exception on one of these additionally iterated elements, the outcome is different.
I don't see any good reason not to use find
.
除了明显(和明显)的开销,是的,结果可能会有所不同。filter
运行到数组末尾,并在每个项目上调用它的回调;相比之下find
,找到一个后停止。当回调在这些额外迭代的元素之一上引发异常时,结果是不同的。
我看不出有什么好的理由不使用find
.
回答by Juan Mendes
Use a polyfill; users.filter(function() { ... } ).shift();
is throwing cycles away while triggering unnecessary garbage collection.
使用polyfill;users.filter(function() { ... } ).shift();
在触发不必要的垃圾收集的同时丢弃循环。
filter
scans the entire array and creates another arrayshift
now has to change all the indexes on the temp array
filter
扫描整个数组并创建另一个数组shift
现在必须更改临时数组上的所有索引
A slightly less wasteful pattern would be to use users.filter(function() { ... } )[0]
一个稍微不那么浪费的模式是使用 users.filter(function() { ... } )[0]