我想知道什么时候应该使用return
,以及什么时候不应该。什么时候/为什么要在回调函数中使用“return”
下面使用的return
对我很困惑。请参阅留言给我的问题:
function each(collection, iterator) {
if (Array.isArray(collection)){
for (var i=0;i<collection.length;i++){
iterator(collection[i],i,collection)
}
}else {
for (var key in collection){
iterator(collection[key],key,collection)
}
}
};
function map(collection, iterator) {
var result = [];
// why we don't add "return" in front of the each() function here?
// why, if I add return, is the result "undefined"?
each(collection,function(value,key,collection){
result.push(iterator(value,key,collection));
})
return result;
};
function pluck(collection, key) {
// Why do we add "return" in front of map function, and
// why if I don't add it, the result is "undefined"?
return map(collection, function(item){
return item[key];
});
};
var car = [{type: "Fiat", model: "500", color: "white"}]
console.log(pluck(car,'type'));