Declaring array of objects

前端 未结 15 1329
遇见更好的自我
遇见更好的自我 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:47
    var ArrayofObjects = [{}]; //An empty array of objects.
    
    0 讨论(0)
  • 2020-12-02 07:48

    Use array.push() to add an item to the end of the array.

    var sample = new Array();
    sample.push(new Object());
    

    To do this n times use a for loop.

    var n = 100;
    var sample = new Array();
    for (var i = 0; i < n; i++)
        sample.push(new Object());
    

    Note that you can also substitute new Array() with [] and new Object() with {} so it becomes:

    var n = 100;
    var sample = [];
    for (var i = 0; i < n; i++)
        sample.push({});
    
    0 讨论(0)
  • 2020-12-02 07:49

    Well array.length should do the trick or not? something like, i mean you don't need to know the index range if you just read it..

    var arrayContainingObjects = [];
    for (var i = 0; i < arrayContainingYourItems.length; i++){
        arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
    }
    

    Maybe i didn't understand your Question correctly, but you should be able to get the length of your Array this way and transforming them into objects. Daniel kind of gave the same answer to be honest. You could just save your array-length in to his variable and it would be done.

    IF and this should not happen in my opinion you can't get your Array-length. As you said w/o getting the index number you could do it like this:

    var arrayContainingObjects = [];
    for (;;){
        try{
            arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
        }
    }
    catch(err){
        break;
    }
    

    It is the not-nice version of the one above but the loop would execute until you "run" out of the index range.

    0 讨论(0)
提交回复
热议问题