繁体   English   中英

如何循环遍历带有条件的 JavaScript 对象然后输出数据?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM