2015-12-07 81 views
0

我想知道什么时候应该使用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')); 

回答

1

使用return有你的函数返回一个值;如果该功能不需要返回任何内容,或者当您不想返回还有时,请不要使用它。

在您的例子,如果你只是说:

function pluck(collection, key) { 
    map(collection, function(item){ 
    return item[key]; 
    }); 
}; 

map()仍然会被调用,但map()的结果将被丢弃。

就好像你写:

function add(a, b) { 
    var c = a + b;   // computed, not returned 
} 

var result = add(1, 2); // undefined 

代替:

function add(a, b) { 
    var c = a + b;   // computed 
    return c;    // and returned 
} 

var result = add(1, 2); // 3 

each()遍历一套东西,每次执行一个动作。它没有结果返回。

而在你的情况下,有更多的代码each()后 - 记住,return;结束从它返回的功能。

// if we returned here 
each(collection,function(value,key,collection){ 
    // this isn't part of each's "value", it's just some code 
    // that runs within the each loop 
    result.push(iterator(value,key,collection)); 
}) 

// we'd never get here, to return the total result 
return result; 
1

不完全相信你的问题是问,但我猜你在这个意义上与map/pluck比较eacheach没有一个明确的说法return何在mappluck确实有一个明确的return声明。

一个关键点要注意的是,即使each没有一个明确的说法return,没有为每个JavaScript函数的隐式return undefined没有明确return声明 - 这意味着each也有一个隐含的return undefined

each没有return声明的原因是因为您没有尝试返回任何内容 - 而是尝试对集合中的每个项目执行某些操作。对于mappluck,大多数库已经定义了它,以便指定这些函数来返回一个集合。

相关问题