简体   繁体   中英

What is the reason to use lodash / underscore .map() function?

In my current project I can see many _.map() usages almost identical like the following example:

var a = [1,2,3,4,5,6,7,8];
var lodashMap = _.map(a, i => {
  if (i < 5) return i-1;
});

And I can't see any reason to not use just built-in Array.map() method like this:

var arrayMap = a.map(i => {
  if (i < 5) return i-1;
});

I know none of these mutates original array and made sure that the result is exactly the same: https://codepen.io/anon/pen/xqPMNQ

Also as we are using Typescript, lodash version loses the i parameter type, so I want to use Array.map() instead. Is there any difference I'm not aware of between Array.map and _.map() ?

For the purposes of the examples you have there, there's no effective difference between the two options and you're just as well off using a.map() .

However, there are some differences between _.map and Array#map .

One is that it can be called directly on array-like objects. (To do so with Array#map requires either attaching the function to the object and then calling it, or using the awkward approach with .call() .)

Example:

 var mapped = _.map(document.getElementsByTagName('li'), el => el.textContent); console.log(mapped);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> <ul><li>A</li><li>B</li><li>C</li></ul>

You can also use _.map on objects that are not array-like. This is something that Array#map can't do at all.

Example:

 var myObj = { a: 1, b : 2 }; var mapped = _.map(myObj, (val, key) => key + val); console.log(mapped);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

It can also be used on null without throwing an error (it just returns an empty array). Depending on how you look at it, you may consider this a good thing or a bad thing, but it's a notable difference from the native .map .

Example:

 var myObj = null; var mapped = _.map(myObj, (val, key) => key + val); console.log(mapped);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Aside from that, there's just the benefit of uniformity if you're combining it with a lot of other lodash/underscore functions.

Also, _.map can be used in an underscore/lodash chain.

Example:

 var values = [{ value: 10 }, { value: 2 }, { value: 13 }, { value: 7 }]; var result = _.chain(values) .map(_.property('value')) .filter(v => v > 5) .sortBy() .value(); console.log(result);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM