搞砸了我的JavaScript返回语句

时间:2015-04-24 09:32:44

标签: javascript function if-statement return

我有一个像这样定义的函数:

  var getPhoneNumber = function (list, phoneType) {
    if (_.isEmpty(list)) {
      return "Not Entered"
    };
    _.each(list, function(phoneNo){

      if (phoneNo.name === phoneType) {
        return phoneNo.value;
      };
    });
    return "Not Entered";
  }

listArray,而phoneTypeString。问题是,即使Not Entered不为空并且list等于phoneNo.name,函数也始终返回值phoneType。如果我在console.log中添加if,则表明条件为真,并打印console.log消息但仍返回Not Entered

1 个答案:

答案 0 :(得分:1)

return phoneNo.value;与函数getPhoneNumber不对应,但函数在_.each处作为回调传递。

你应该尝试这样的事情:

var getPhoneNumber = function (list, phoneType) {
    var value = null;
    _.each(list, function(phoneNo){

      if (phoneNo.name === phoneType) {
        value = phoneNo.value;
      }
    });

    if(value !== null)
        return value;
    else
        return "Not Entered";
  }