我有一個Product javascript數組,其中包含所有產品信息。 創建一個在此數組上迭代並通過匹配id來查找產品的函數。Javascript函數返回false發現連對象
var products = JSON.parse('[{"Product":{"id":"1","name":"My Product","description":"This is my new product","price":"10.00","currency":"$","stock":"0","image":"/image1.png"}},{"Product":{"id":"5","name":"Dummy Product 2","description":"Some dummy text goes here.","price":"10.00","currency":"$","stock":"100","image":"image2.jpg"}}]');
$(document).ready(function(){
console.log(products);
alert(findProduct(5)); //it will returns false everytime, evan it has matching product
});
function findProduct(product_id){
$.each(products, function(k, v){
if(v.Product.id == product_id){
console.log(v);
return products[k]; //or return 'v'
}
});
return false;
}
入住這Demo
功能每次返回false,即使找到了匹配的產品ID,不知道爲什麼?如果我將匹配的數組鍵存儲在一個變量中並在迭代後返回該鍵的值,它將返回適當的對象。但那不是正確的方法,因爲我想停止迭代並返回找到對象的值。
'return result;'maybe? – Tony
是的,修好了。謝謝你的提示。 –