Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create js array dynamically?

how could I declare several js array dynamically? For example, here is what tried but failed:

 <script type="text/javascript">
 for (i=0;i<10;i++)
 {
   var "arr_"+i = new Array();
 } 

Thanks!

like image 409
WilliamLou Avatar asked Dec 09 '09 23:12

WilliamLou


People also ask

Are arrays in JS dynamic or fixed?

Normally, we determine the array size or length while creating it; this array type is a static or fixed array. On the other side, the dynamic array means allocating the memory and populating the values at run time.

How do you dynamically add values to an array of objects in JavaScript?

There are two ways to dynamically add an element to the end of a JavaScript array. You can use the Array. prototype. push() method, or you can leverage the array's “length” property to dynamically get the index of what would be the new element's position.


2 Answers

You were pretty close depending on what you would like to do..

<script type="text/javascript">
    var w = window;
     for (i=0;i<10;i++)
     {
       w["arr_"+i] = [];
     }
</script>

Would work, what is your intention for use though?

like image 141
Quintin Robinson Avatar answered Sep 24 '22 10:09

Quintin Robinson


make it an array of arrays:

var arr = [];  // creates a new array .. much preferred method too.
for (var i = 0; i < 10; i++) {
    arr[i] = [];
}
like image 38
nickf Avatar answered Sep 24 '22 10:09

nickf