creating and parsing a 3D array in javascript? [duplicate]
can any one help me to create and parse a 3d array in javascript.
im having a questionId each question Id have a selected option and an optional option text.
so i need to create a 3d array for questionId,optionId,optionText(string)..
Thnks in advance
A one dimension array would be:
var myArr = new Array();
myArr[0] = "Hi";
myArr[1] = "there";
myArr[2] = "dude";
alert(myArr[1]); // Alerts 'there'
A two dimensional array would be:
var myArr = new Array();
myArr[0] = new Array("Val", "Va");
myArr[1] = new Array("Val", "yo");
myArr[2] = new Array("Val", "Val");
alert(myArr[1][1]); // Alerts 'yo'
A 3D array is more complicated, and you should evaluate your proposed use of it as it has a limited scope within the web. 99% of problems can be solved with 1D or 2D arrays. But a 3D array would be:
var myArr = new Array();
myArr[0] = new Array();
myArr[0][0] = new Array()
myArr[0][0][0] = "Howdy";
myArr[0][0][1] = "pardner";
alert(myArr[0][0][1]); // Alerts 'pardner'
var data = new Array();
data starts off as a regular one-dimensional array. A two dimensional array is really just an array of arrays. So you could do something like
for (var i = 0; i<numberOfQuestions; i++){
data[i] = new Array();
data[i][0] = something;
data[i][1] = somethingElse;
}
Alternatively you could use the following approach
for (var i = 0; i<numberOfQuestions; i++){
data.push([something, somethingElse]);
}
In any case, at some point you are going to need a loop to populate your initial array with sub-arrays to get the 2d effect.
Okay, so as I said in comment to the question, I think you actually need 2D array. That is, if you have N number of questionIds and each questionId has two properties: optionId and optionText
You can create it somehow like this:
var twoD = new Array();
twoD[1] = new Array();
twoD[1]['optionId'] = 3;
twoD[1]['optionText'] = 'blabla';
twoD[2] = new Array();
twoD[2]['optionId'] = 5;
twoD[2]['optionText'] = null;
alert(twoD[1]['optionId']);
Although note that array with associative key is actually an object in JavaScript.
Update: looping through JavaScript
for(var question : twoD){
alert(question['optionId']);
alert(question['optionText']);
}
hi you can create the nth dimension error in javascript one of the example is below
var apple = new Array(); apple[1] = new Array(); apple[1][1] = new Array(); apple[1][1][1] = 'yourname'
now you can use the recursive function to iterate through the array and check and pare every thing.
精彩评论