JS 物件與陣列互相巢狀的複雜例子

katesharing發表於2024-08-15

JS寫法如下:

 const myObj = {
        name: "John",
        age: 30,
        cars: [
            { name: "Ford", models: ["Fiesta", "Focus", "Mustang"] },
            { name: "BMW", models: ["320", "X3", "X5"] },
            { name: "Fiat", models: ["500", "Panda"] }
        ]
    }

    //官方例子寫法
    let x = "";
    for (let i in myObj.cars) {
        x += "<h1>" + myObj.cars[i].name + "</h1>";
        for (let j in myObj.cars[i].models) {
            x += myObj.cars[i].models[j] + "<br>";
        }
    }
    document.getElementById("demo").innerHTML = x;

    //存疑寫法,如果只想models裡的數值一次性輸出,是不是可以少寫一次迴圈?
    let y = "";
    for (let i in myObj.cars) {
        y += "<h1>" + myObj.cars[i].name + "</h1>";
        y += myObj.cars[i].models + "<br>";
    }
    
    document.getElementById("demo2").innerHTML = y;

1. 官方例子測試結果如下:

2. 存疑例子測試如下:

相關文章