Declaring array of objects

前端 未结 15 1455
遇见更好的自我
遇见更好的自我 2020-12-02 07:01

I have a variable which is an array and I want every element of the array to act as an object by default. To achieve this, I can do something like this in my code.



        
15条回答
  •  被撕碎了的回忆
    2020-12-02 07:38

    You don't really need to create blank Objects ever. You can't do anything with them. Just add your working objects to the sample as needed. Use push as Daniel Imms suggested, and use literals as Frédéric Hamidi suggested. You seem to want to program Javascript like C.

    var samples = []; /* If you have no data to put in yet. */
    /* Later, probably in a callback method with computed data */
    /* replacing the constants. */
    samples.push(new Sample(1, 2, 3)); /* Assuming Sample is an object. */
    /* or */
    samples.push({id: 23, chemical: "NO2", ppm: 1.4}); /* Object literal. */
    

    I believe using new Array(10) creates an array with 10 undefined elements.

提交回复
热议问题