Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

ecmascript 6 - Difference between find() and filter().shift() on javascript

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() { ... } );

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

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...