if I define a multi-dimentional javascript array like this
//var myStack = new Array(3);
// *** edit ***
var myStack = {};
What is the best way to insert one value at a time?
myStack[1][1][0] = myValue;
I want to read a database and write one value at a time. Example:
myStack[recordNo][1]['FirstName'] = myValue;
if I define a multi-dimentional javascript array like this
//var myStack = new Array(3);
// *** edit ***
var myStack = {};
What is the best way to insert one value at a time?
myStack[1][1][0] = myValue;
I want to read a database and write one value at a time. Example:
myStack[recordNo][1]['FirstName'] = myValue;
Share
Improve this question
edited Dec 25, 2011 at 20:03
Bakudan
19.5k9 gold badges55 silver badges75 bronze badges
asked Dec 25, 2011 at 17:58
Mustapha GeorgeMustapha George
2,52710 gold badges49 silver badges86 bronze badges
1
- 6 var myStack = new Array(3); does not define a 3-dimensional array, it creates a 1-dimensional array with 3 entries – Dexygen Commented Dec 25, 2011 at 18:05
4 Answers
Reset to default 9Inserting a single value can be done through one line of code:
myStack[1] = [,[value]];
Or, the long-winded way:
myStack[1] = [];
myStack[1][1] = [];
myStack[1][1][0] = value;
Either method will populate the array myStack
with multiple arrays, and finally set the desired value, as requested at the question.
EDIT: As a response to the updated question, the following can be used:
myStack[recordNo] = [,{'FirstName': myValue}];
To avoid dealing with an array index for every dimensions (which could lead to mistakes if you don't pay attention for a second), you can use a push
approach. It makes it easier to read / debug, especially when you have a great number of dimensions :
// some constants for navigation purpose
var FIELD_FNAME=0;
var FIELD_LNAME=1;
var FIELD_JOB=2;
// initialize your stack
var myStack=[];
// create a new row
var row = [];
var fname = "Peter";
row.push(fname);
var lname = "Johnson";
row.push(lname);
var job = "Game Director";
row.push(job);
// insert the row
myStack.push(row);
Then it would be possible to iterate like this :
for (var i=0;i<myStack.length;i++) {
var row = myStack[i];
var fname = row[FIELD_FNAME];
var lname = row[FIELD_LNAME];
var job = row[FIELD_JOB];
}
for example:
var varname={};
for (var k = 0; k < result.rows.length; k++) {
varname[k] =
{
'id': result.rows.item(k).id,
'name': result.rows.item(k).name
};
}
You can use three for
loops, if you are inserting all of the values into the array at one time:
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
for (var k = 0; k < 3; k++) {
myStack[i][j][k] = myValue;
}
}
}