Reputation: 91
This is a very strange to me actually. I can't figure out how create a multidimensional array dynamically. I want to create a three-level drop-down list, so I think I need a three dimensional array to store the values. How to create three dimensional array?
<script language=javascript>
var aCourse=new Array();
aCourse[0]=new Array();
aCourse[1]=new Array();
aCourse[2]=new Array();
aCourse[3]=new Array();
aCourse[0][0]="Select...";
aCourse[1][0]="Select...";
aCourse[1][1]="T Square";
aCourse[1][2]="V Square";
aCourse[1][3]="S Square";
aCourse[1][4]="B Square";
aCourse[1][5]="G Square";
aCourse[2][0]="Select...";
aCourse[2][1]="N Square";
aCourse[2][2]="W Square";
aCourse[3][0]="Select…";
aCourse[3][1]="J Square";
aCourse[3][2]="M Square";
function ChangeCourse()
{
var i,
iCategoryIndex;
iCategoryIndex=document.frm.optCategory.selectedIndex;
iCourseCount=0;
while (aCourse[iCategoryIndex][iCourseCount]!=null)
iCourseCount++;
document.frm.optCourse.length=iCourseCount;
for (i=0;i<=iCourseCount-1;i++)
document.frm.optCourse[i]=new Option(aCourse[iCategoryIndex][i]);
document.frm.optCourse.focus();
}
</script>
<body ONfocus=ChangeCourse()>
<h3>Choose category…</h3>
<form name="frm">
<p>Category:
<select name="optCategory" size="1" onChange=ChangeCourse()>
<option>Select…</option>
<option>Soccer</option>
<option>Cricket</option>
<option>Rugby</option>
</select>
</p>
<p>Fields
<select name="optCourse" size="1">
<option>Select…</option>
</select>
</p>
</form>
Upvotes: 0
Views: 566
Reputation: 96800
First, it's always good to initialize arrays using square brackets, []
:
var aCourse = [];
And to simulate multidimensional arrays in JS, which is essentially an indeterminate number of arrays inside of a single array, do this:
aCourse[0] = [];
Or you could create the arrays inside of the square brackets when creating the array:
var aCourse = [
[], [], []
];
This is equivalent to:
aCourse[0] = [];
aCourse[1] = [];
aCourse[2] = [];
Upvotes: 0
Reputation: 12613
If your only problem is creating the three-dimensional array, this should work:
var aCourse = [];
for(var i = 0; i < dimensionOneSize; i++) {
aCourse[i] = [];
for(var k = 0; k < dimensionTwoSize; k++)
aCourse[i][k] = [];
}
It is good to note that JavaScript supports the short-hand definition of an array with square brackets []
, so you can use those to make the dynamic definition cleaner.
Also, I'm not sure if this works very well, but it might:
var aCourse = [[[]]];
So far, my testing has not proven a way to use this, but it does validate as a proper script.
Upvotes: 1