2014-02-24 93 views
0

我有一個函數默認情況下返回null,另一個值是條件。JavaScript函數忽略返回語句

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; 
}; 

找到正確的數組條目。但返回狀態不會返回它, 它被忽略。

+0

你是如何調用這個函數? – RononDex

+0

你可以顯示使用返回值的代碼嗎? –

+0

我只是把它叫做alert(getName(boxid)); if函數的返回語句不是結束函數嗎? – marcel

回答

5

您的return語句不工作的原因是因爲它是本地forEach的回調,並沒有涉及到你的getName - 功能。

你應該使用正常for -loop代替:

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; 
}; 
+0

工作,感謝您的解釋 – marcel

1

因爲它們處於不同的範圍。

你可以使用filtermap功能:

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. 
+0

它返回整個boxex-content。 – marcel

1

return box.name;是內部forEach功能。

功能getName只有return null;