问题描述
环顾四周,但找不到这个问题。 Underscore(或 Lodash)_.map
和 JavaScript 内置的 map
函数之间有什么实际区别吗?我可以互换使用它们吗?
即:是
_.map(myArr,a => {
// do stuff...
})
等于
myArr.map(a => {
// do stuff...
}
解决方法
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
支持方便的 iteratee 速记,而 Array.prototype.map
不支持:
map([[1,2,3],[4,5],[6]],'length'); // [3,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,bindObject);
// [ 'Goodbye Joe','Goodbye Jane' ]
您通常可以安全地将 Array.prototype.map
替换为 Underscore 的 map
,但反过来不行。
它们是不同的功能;如果您查看 Lodash's source code for map
,您会发现它不使用 <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
Vue.config.devtools = true;
Vue.config.productionTip = false;
Vue.filter("time",function(date) {
return date.toISOString().split('T')[1].slice(0,-1)
});
function randomInt(min,max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
</script>
<div id="app">
<bar-chart :data="data" :width="width" />
</div>
“幕后”。
主要区别在于 Lodash “保护”了它的一系列函数以在其 Array.prototype.map
(以及类似的迭代函数)中使用。来自 Lodash 文档 (https://lodash.com/docs/4.17.15#map):
受保护的方法有:ary、chunk、curry、curryRight、drop、 dropRight,每个,填充,反转,parseInt,随机,范围,范围右, 重复,sampleSize,切片,一些,sortBy,拆分,采取,采取权, 模板、修剪、修剪结束、修剪开始和单词