【问题标题】:Is there any difference between Underscore _.map and the JS built-in function?Underscore _.map 和 JS 内置函数有什么区别吗?
【发布时间】:2021-04-16 19:32:33
【问题描述】:

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

即:是

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

等于

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

【问题讨论】:

  • 它们不可互换。 Lodash 的版本采用不同类型的参数。检查每个文档。

标签: javascript lodash underscore.js


【解决方案1】:

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,但反之则不行。

【讨论】:

    【解决方案2】:

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

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

    受保护的方法有:ary、chunk、curry、curryRight、drop、 dropRight,每个,填充,反转,parseInt,随机,范围,rangeRight, 重复,sampleSize,切片,一些,sortBy,拆分,采取,takeRight, 模板、trim、trimEnd、trimStart 和单词

    【讨论】:

    • 这里的“守卫”是什么意思?这些方法在您链接的源中列出在哪里?
    • “受保护”意味着它们可以安全地用作 _.map 等函数的迭代对象。保护方法的一个很好的例子是_.parseInt。如果将它用作迭代对象,则不会使用它的第二个参数 radix,即使 _.map 传递了三个参数。如果你使用parseInt,你会得到意想不到的行为。
    • 我设置的一个基本演示来展示这个:jsfiddle.net/nb0vte4y
    • 保护可以说是相关保护函数的属性,而不是_.mapArray.prototype.map 之间的区别。我当然不会称其为主要区别,因为在 Underscore 和 Lodash 中有很多您无法从标准中获得的功能。
    猜你喜欢
    • 2019-03-31
    • 2018-03-08
    • 2016-12-24
    • 2023-03-04
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多