6

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!

WilliamLou
  • 1,914
  • 6
  • 27
  • 38

4 Answers4

8

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?

Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132
  • 6
    @Tim Whitlock Perhaps you could elaborate on your statement and completely explain scope and preferred JS programming techniques to the OP for his simple question. – Quintin Robinson Dec 09 '09 at 23:10
  • 2
    Yes, and explain how you can write any program with zero globals. – Kon Dec 09 '09 at 23:11
5

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] = [];
}
nickf
  • 537,072
  • 198
  • 649
  • 721
2

You can put them all into an array, like this...

var arrContainer = [];

 for (i=0;i<10;i++)
 {
   arrContainer.push(new Array());
 }
Kon
  • 27,113
  • 11
  • 60
  • 86
0

Try [...new Array(10)]. It is short and handy.

Bubunyo Nyavor
  • 2,511
  • 24
  • 36