Pluck函数基于map函数:
_.map = function(collection, iterator) {
var result = [];
_.each(collection,function(value,key,collection){
result.push(iterator(value,key,collection));
})
return result;
};
如何在不使用地图功能的情况下编写下面的弹拨功能,但仍然以相同的方式工作......?用于循环?
_.pluck = function(collection, key) {
return _.map(collection, function(item){
return item[key];
});
};
var car = [{ type: "Fiat", model: "500", color: "white" }];
console.log(pluck(car, 'type')); //"Fiat"
另外,如何在不使用reduce函数的情况下编写contains函数:
_.reduce = function(collection, iterator, accumulator) {
accumulator = iterator(accumulator,value);
});
return accumulator;
};
_.contains = function(collection, target) {
return _.reduce(collection, function(wasFound, item) {
if (wasFound) {
return true;
}
return item === target;
}, false);
};
contains([1,2,3],3) //true
最后......如何编写shuffle函数......根据underscore.js。 随机播放功能: shuffle_.shuffle(列表)
Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle.
_.shuffle([1, 2, 3, 4, 5, 6]);
=> [4, 1, 6, 3, 5, 2]
答案 0 :(得分:0)
使用简单的for
循环:
function pluck(arr, key) {
var out = [];
for (var i = 0, l = arr.length; i < l; i++) {
if (arr[i][key]) out.push(arr[i][key]);
}
return out;
}
pluck(car, 'type');
contains
:
function contains(arr, key, from) {
for (var i = from || 0, l = arr.length; i < l; i++) {
if (arr[i] === key) return true;
}
return false;
}
contains(arr, 2, 1);