Underscore _.map 和JS内置函数有区别吗?

Is there any difference between Underscore _.map and the JS built-in function?

环顾四周,但找不到这个问题。 Underscore(或 Lodash)_.map 和 JavaScript 内置的 map 函数之间有什么实际区别吗?我可以互换使用它们吗?

即:是

_.map(myArr, a => {
  // do stuff...
})

等于

myArr.map(a => {
  // do stuff...
}

它们是不同的函数;如果您查看 Lodash's source code for map,您会发现它确实 而不是 使用 Array.prototype.map “在幕后”。

主要区别在于 Lodash“保护”了它的一堆函数,以便在其 map(和类似的迭代函数)中使用。来自 Lodash 文档 (https://lodash.com/docs/4.17.15#map):

The guarded methods are: ary, chunk, curry, curryRight, drop, dropRight, every, fill, invert, parseInt, random, range, rangeRight, repeat, sampleSize, slice, some, sortBy, split, take, takeRight, template, trim, trimEnd, trimStart, and words

Array.prototype.map 和 Underscore(或 Lodash)的独立 map 函数之间有两个主要区别。

首先,map 适用于没有 length 属性 的对象,而 Array.prototype.map 不适用:

import { map } from 'underscore';

const square = x => x * x;
const obj = {a: 1, b: 2, c: 3};

map(obj, square); // fine, [1, 4, 9]
[].map.call(obj, square); // error

其次,与所有 Underscore 集合函数一样,map 支持 Array.prototype.map 不支持的方便的迭代速记:

map([[1, 2, 3], [4, 5], [6]], 'length'); // [3, 2, 1]

const people = [
    {name: 'Joe', occupation: 'news presenter'},
    {name: 'Jane', occupation: 'firefighter'},
];

map(people, 'occupation');
// ['news presenter', 'firefighter']

map(people, ['occupation', 2]);
// ['w', 'r'] (third character of occupation)

map(people, {name: Jane}); // [false, true]

一个仅适用于 Underscore 的更小的区别是 map 支持可选的第三个参数,使您可以将回调绑定到此参数:

const sourceObject = {
    greet(name) {
        return this.greeting + name;
    },
    greeting: 'Hello ',
};

const bindObject = {
    greeting: 'Goodbye ',
};

const names = map(people, 'name');

map(names, sourceObject.greet, sourceObject);
// [ 'Hello Joe', 'Hello Jane' ]

map(names, sourceObject.greet, bindObject);
// [ 'Goodbye Joe', 'Goodbye Jane' ]

您通常可以安全地将 Array.prototype.map 替换为下划线的 map,但反之则不然。