我有一个函数默认返回 null,并根据条件返回另一个值。
var getName = function(boxid){
var boxes = localStorage.getItem("boxes");
if((boxes != "" )&& (typeof boxes != "undefined") &&( boxes != null))
{
boxes = JSON.parse(boxes);
boxes.forEach(function(box){
if(box.id == boxid)
{
console.log("box.name: "+ box.name+ " boxid: "+ box.id+ " : "+ boxid);
return box.name;
}
});
}
return null;
};
找到正确的数组条目。但 return 语句不返回它, 它被忽略了。
最佳答案
您的 return 语句不起作用的原因是它是 forEach
回调的本地函数,与您的 getName
函数无关。
您应该使用普通的 for
循环:
var getName = function(boxid){
var boxes = localStorage.getItem("boxes");
if((boxes != "" )&& (typeof boxes != "undefined") &&( boxes != null))
{
boxes = JSON.parse(boxes);
for(var i = 0; i < boxes.length; i++) {
if(boxes[i].id == boxid)
{
console.log("boxName: "+ boxes[i].name+ " boxID: "+ boxes[i].id+ " : "+ boxid);
return boxes[i].name;
}
};
}
return null;
};
关于javascript函数忽略return语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21982992/