Declaring array of objects

前端 未结 15 1401
遇见更好的自我
遇见更好的自我 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: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.

提交回复
热议问题