[英]javascript function ignores return statement
我有一个函数默认情况下返回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 statemant不返回它,它被忽略。
您的return语句不起作用的原因是因为它在forEach
的回调中是本地的,与getName
-function不相关。
您应该for
-loop使用普通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;
};
因为它们属于不同的范围。
您可以使用filter
和map
功能:
boxes = JSON.parse(boxes);
// the result will be an array of box name
return boxes.filter(function(box){
return box.id = boxid;
}).map(function(box) {
return box.name;
});
// if the box id is unqic, then just get the first one.
return box.name;
用于forEach
的函数。
函数getName
仅return null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.