javascript上find()和filter()。shift()之间的区别 [英] Difference between find() and filter().shift() on javascript

查看:161
本文介绍了javascript上find()和filter()。shift()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始放弃下划线/ lodash过度使用(部分)我的项目,并意识到没有完全支持 find 方法。 ES6方法查找和使用之间有什么区别.shift()通过过滤结果

I recently starting to drop underscore/lodash overuse on (some of) my projects and realize that there's no full support of find method in browsers. What's the difference between ES6 method find and using .shift() over filter results

var user = users.find(function() { ... } );

var user = users.filter(function() { ... } ).shift();

我想在查找方法上有明显的优化(停止迭代拳头比赛),但我可以使用第二种方法获得意外结果?我应该使用 polyfill 吗?为什么?

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 polyfill instead? Why?

推荐答案

除了明显的(明显的)开销之外,是的,结果可能会有所不同。 filter 运行到数组的末尾,并在每个项目上调用它的回调;与找到相反,它在找到之后停止。当回调在这些额外迭代的元素之一上抛出异常时,结果是不同的。

我没有看到任何有理由不使用 find

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.

这篇关于javascript上find()和filter()。shift()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆