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 替换为 Underscore 的 map,但反之则不行。