[英]How to loop through a JavaScript object with a condition and then output the data?
我做了兩輛車:
var manana = {name: "manana", price: "$8,000", slots: "4"};
var walton = {name: "walton", price: "$12,000", slots: "7"};
對按鈕點擊做出反應,我想檢查一個條件,看看哪輛車的價格等於 8,000 美元,槽位等於 4。如果是,它會在表格中輸出它。
您需要在按鈕上連接一個事件。 然后循環瀏覽您的車輛並測試狀況。 就像是:
var manana = {name: "manana", price: "$8,000", slots: "4"};
var walton = {name: "walton", price: "$12,000", slots: "7"};
var vehicles = [manana, walton];
function eval() {
for (var i = 0; i < vehicles.length; i++) {
var vehicle = vehicles[i];
if (vehicle.price == '$8,000' && vehicle.slots == '4')
alert('found ' + vehicle.name);
}
}
這是 JSfiddle: https ://jsfiddle.net/10qjw1gm/1/
這是我的答案,您可以重用具有不同價格和插槽條件或其他數組的函數:
var myArray = [{name: "manana", price: "$8,000", slots: "4"}, {name: "walton", price: "$12,000", slots: "7"}];
function retrieveNameUsingPriceAndSlots(pArray, pPrice, pSlots) {
for(var i = 0; i < pArray.length; i++) { //Loop through the array
var item = pArray[i];
if(item.price === pPrice && item.slots === pSlots) {
//If the item meets our condition, returns the name, and the code after this line wont be executed.
return item.name;
}
}
return false;
}
console.log(retrieveNameUsingPriceAndSlots(myArray, "$8,000", "4")); //manana
小提琴: http : //jsfiddle.net/g2zuhou0/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.