我拉一個空白,爲什麼這個代碼不按預期工作(jsFiddle here):Javascript和/或jQuery能以這種方式返回對象嗎?
data = [
{
"id": 1,
"value": 4.56
},
{
"id": 2,
"value": 7.89
}];
function FindMe(searchID)
{
$.each(data, function (i, v)
{
// i=index, v=value (which is an object)
if (v.id === searchID)
{
console.log("Found: ");
console.log(v);
return v; // pass the desired object back to caller
}
});
}
console.clear();
var test = FindMe(2); // causes the console to show the correct object
console.log("Returned: ");
console.log(test); // shows "undefined" instead of a returned object
功能明確,它的工作,以找到正確的數組元素(控制檯顯示這是「發現「),但回報沒有發生。這裏有什麼問題?
現在我明白了 - 謝謝。不值得downvote雖然... –
@GeekStocks我沒有downvote,順便說一句 –