2014-04-13 50 views
0

我拉一個空白,爲什麼這個代碼不按預期工作(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 

功能明確,它的工作,以找到正確的數組元素(控制檯顯示這是「發現「),但回報沒有發生。這裏有什麼問題?

回答

4

這是因爲循環函數返回找到的項目,而不是函數FindMe。

找到我什麼都不返回。

function FindMe(searchID) { 
var result;  
    $.each(data, function (i, v) { // i=index, v=value (which is an object) 
     if (v.id === searchID) { 
      console.log("Found: "); 
      console.log(v); 
      result = v; // pass the desired object back to caller 
      return false; 
     } 
    }); 
    return result; 
} 
+0

現在我明白了 - 謝謝。不值得downvote雖然... –

+0

@GeekStocks我沒有downvote,順便說一句 –

2

您的FindMe函數沒有return聲明。你只是打電話$.each ...

0

你可以使用:

data = [{ 
"id": 1, 
    "value": 4.56 
}, { 
    "id": 2, 
     "value": 7.89 
}]; 


function FindMe(searchID) { 
    var searchObj=null; 
    $.each(data, function (i, v) { // i=index, v=value (which is an object) 
     if (v.id === searchID) { 
      console.log("Found: "); 
      console.log(v); 
      searchObj = v; // pass the desired object back to caller 
      return false; 
     } 
    }); 
    return searchObj; 
} 

console.clear(); 
var test = FindMe(2); 
object 
console.log("Returned: "); 
console.log(test); 
object 
相關問題