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!
asked Dec 9, 2009 at 23:03
WilliamLou
1,9046 gold badges28 silver badges38 bronze badges
4 Answers 4
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?
answered Dec 9, 2009 at 23:05
Quintin Robinson
82.6k14 gold badges128 silver badges132 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Quintin Robinson
@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.
Kon
Yes, and explain how you can write any program with zero globals.
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] = [];
}
answered Dec 9, 2009 at 23:05
nickf
548k199 gold badges660 silver badges727 bronze badges
Comments
You can put them all into an array, like this...
var arrContainer = [];
for (i=0;i<10;i++)
{
arrContainer.push(new Array());
}
answered Dec 9, 2009 at 23:06
Kon
27.5k12 gold badges64 silver badges87 bronze badges
Comments
Try [...new Array(10)]. It is short and handy.
answered Oct 31, 2018 at 21:20
Bubunyo Nyavor
2,5701 gold badge26 silver badges37 bronze badges
Comments
lang-js