在javascript中处理多个返回值

时间:2015-06-17 05:41:45

标签: javascript

最后我自己写了一个问题因为我在这里读了其他问题,但仍然不明白为什么我的代码不起作用。也许有人可以解释我的错误?

代码运行直到搜索名称“Joe”,然后它说par2没有定义...为什么?在搜索功能之后的检查中,我可以清楚地看到参数par1和par2都返回...

var friends = {};
friends.bill = {
  firstName: "Bill",
  lastName: "Gates",
  number: "(206) 555-5555",
  address: ['One Microsoft Way', 'Redmond', 'WA', '98052']
};
friends.steve = {
  firstName: "Steve",
  lastName: "Jobs",
  number: "(408) 555-5555",
  address: ['1 Infinite Loop', 'Cupertino', 'CA', '95014']
};

function list(obj) {
  for (var prop in obj) {
    console.log(prop);
  }
};

function bettersearch(name2) {
  var sna = name2
  for (var prop in friends) {
    if (friends[prop].firstName === name2) {
      // console.log("Value found :",friends[prop]);
      return {
        par1: friends[prop],
        par2: sna
      }
    }
  }
};

// Test if the variables are returned
var test = bettersearch("Bill")
console.log("\n\n",test);
console.log("\n\n",test.par1);
console.log("\n\n",test.par2);


//Formatting function for a nice Output
function format(obj) {
  if (obj) {
    var result = "";
    result += "\nName:  " + obj.par1.firstName + " " + obj.lastName;
    result += "\nNumber:  " + obj.par1.number;
    result += "\nAddress: " + obj.par1.address.join(', ');
    console.log(result);
  } else {
    console.log("\nDer Name", obj.par2, "wurde nicht gefunden");
  }
}

//Call the functions
format(bettersearch("Bill"));
format(bettersearch("Steve"));
format(bettersearch("Joe"));

3 个答案:

答案 0 :(得分:3)

  

然后它说par2没有定义......

不,它没有。它说的是Cannot convert 'obj' to objectCannot access 'par2' on undefined

  

为什么?

因为bettersearch函数在找不到名称时不会返回任何。在format函数中,您明确检查是否存在obj,但尽管它是undefined,您仍尝试访问obj.par2

我认为你在寻找

function bettersearch(name) {
  for (var prop in friends)
    if (friends[prop].firstName === name)
      return {
        friend: friends[prop],
        name: name
      };
  return {
    name: name
  }; // always return a result object
}

function format(obj) {
  if (obj.friend) {
    var result = "";
    result += "\nName:  " + obj.friend.firstName + " " + obj.friend.lastName;
    result += "\nNumber:  " + obj.friend.number;
    result += "\nAddress: " + obj.friend.address.join(', ');
    console.log(result);
  } else {
    console.log("\nDer Name", obj.name, "wurde nicht gefunden");
  }
}

答案 1 :(得分:1)

这可能是构建数据和编写search函数

的更好方法
var friends = [
    {
      firstName: "Bill",
      lastName: "Gates",
      number: "(206) 555-5555",
      address: ['One Microsoft Way', 'Redmond', 'WA', '98052']
    },
    {
      firstName: "Steve",
      lastName: "Jobs",
      number: "(408) 555-5555",
      address: ['1 Infinite Loop', 'Cupertino', 'CA', '95014']
    }

];

function searchFriends(firstName) {
  return friends.filter(function(f) {
    return f.firstName === firstName;
  });
}
console.log(searchFriends("Bill"));
//=> [{"firstName":"Bill","lastName":"Gates","number":"(206) 555-5555","address":["One Microsoft Way","Redmond","WA","98052"]}]

console.log(searchFriends("Steve"));
//=> [{"firstName":"Steve","lastName":"Jobs","number":"(408) 555-5555","address":["1 Infinite Loop","Cupertino","CA","95014"]}]

console.log(searchFriends("Joe"));
//=> []

我提出这个建议是因为在你的代码中,很容易有重复。

例如John SmithJohn Smyth怎么办?两者都会使用friends.john ...

如果您希望搜索结果返回查询和匹配

function searchFriends(firstName) {
  return {
    search: firstName,
    result: friends.filter(function(f) {
      return f.firstName === firstName;
    })
  };
}

以同样的方式使用

console.log(searchFriends("Steve"));
// {
//   search: "Steve",
//   result: [{"firstName":"Steve","lastName":"Jobs","number":"(408) 555-5555","address":["1 Infinite Loop","Cupertino","CA","95014"]}]
// }

console.log(searchFriends("Joe"));
// {
//   search: "Joe",
//   result: []
// }

答案 2 :(得分:0)

实际错误是

  

“TypeError:无法读取未定义的属性'par2'

您的错误位于console.log()行,其中if(obj)返回false(表示没有对象 - 实际上未定义):

console.log("\nDer Name", obj.par2, "wurde nicht gefunden");

完全删除该行。