Referencing a javascript object literal array

后端 未结 5 1868
旧时难觅i
旧时难觅i 2021-02-08 22:57

How would you reference the models (Accord, CRV, Prius, etc) in this structure? Is this a bad structure to be able to extract the makes...then use a make to get the models...th

5条回答
  •  野性不改
    2021-02-08 23:36

    Jonathan's is correct, but he missed the additional level of Array's at the model level, so it should be

     cars[0].models[0].Accord
     cars[0].models[1].CRV
    

    etc

    I suspect you would find it easier to use a structure along the lines of:

    var cars = [
    {makes  : "Honda",
     models  : {
        Accord : ["2dr","4dr"],
        CRV  : ["2dr","Hatchback"],
        Pilot: ["base","superDuper"]  
     }
    }, 
    {makes   :"Toyota",
     models  : {
        Prius   : ["green","reallyGreen"],
        Camry   : ["sporty","square"],
        Corolla : ["cheap","superFly"]
     }
    }];
    

    In which the models array is replaced by an object (or associative array if you like)

    [edit (olliej): tidying up code in second example]

提交回复
热议问题