如何循环使用条件遍历JavaScript对象,然后输出数据

How to loop through a JavaScript object with a condition and then output the data?

本文关键字:对象 JavaScript 遍历 然后 数据 输出 条件 何循环 循环      更新时间:2023-09-26

我做了两辆车:

var manana = {name: "manana", price: "$8,000", slots: "4"};
var walton = {name: "walton", price: "$12,000", slots: "7"};

当我点击一个按钮时,我想检查一下情况,看看哪辆车的价格既等于8000美元,又等于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);
    }
}

这是jsfield: 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/