I could use some guidance on specifying a dynamic multi dimensional array in javascript. I understand that javascript does not natively define multi dim arrays, but rather a
All arrays are dynamic in javascript. You can do things like
var list = [];
list[15] = 15;
And it will simply expand the array to have a length of 16, with the values for the first 15 indexes being undefined (~ null). Thus, your 3 examples of multi-dimensional arrays should all work.
Edit: Just saw that you included your code. You are not initializing the arrays of your first dimension. Your loop should be
for (i = 0; i < recCount; i++) {
//If the outer array does not have an inner array at this position already, create one
if (!myArray[i])
myArray[i] = []; //!!!
for (s = 0; s < 15; s++) {
// myArray[i] = new Array(14);
myArray[i][s] = coordsAry[n]; //myArray[i] returned null/undefined, when i got bigger then the declared array.
n++;
// alert("i=" + i + " s=" + s + " Val: " + (myArray[i][s]));
}
// var u = 4;
s = 0;
alert(myArray[0][3]);
alert(myArray[0][4]);
alert("i=" + i + " s=" + s + " Val: " + (myArray[i][s]));
}
To add an element to an array you can use push(val) (to add the back of the array) or unshift(val) to add to the front of the array. So:
var Exforsys=[];
for (i=0; i <4; i++) {
Exforsys.push([]);
}
You do not Dim the Array to an actual size,
You can just set an variable on any index to whatever you want
if you want two Dimensions you just could define an array
var arr = []
set an element to another array
arr[0] = []
and put an value inside an element in the "2nd dimension"
arr[0][10] = 10
You only have the elements in the "first dimension" to be an array
You could also do things like placing arrays into arrays
like
var arr = []
var arr1 = [1,2,3]
arr[0] = arr1
console.log(arr[0][2]) //3
And if you have an array and want to push elements in an inner array just do a check if the element is defined, like
var arr = []
for ( var i = 0; i < 5 ; i++) {
if(!arr[i])
arr[i] = []
for ( var j = 0; j < 3 ; j++)
arr[i][j] = i + " - " + j // Or like this,
//arr[i].push(i + " " + j) //
}
console.log( arr[2][3]) // 2 - 3
function newTest() {
var myArray = [[],[]];
// myArray[] = new Array(14);
var recCount = 15
var n =0;
var i = 0;
var s = 0;
for (i = 0; i < recCount; i++) {
if(!myArray[i])
myArray[i] = []
for (s = 0; s < 15; s++) {
console.log(i)
// myArray[i] = new Array(14);
myArray[i][s] = s;
n++;
// alert("i=" + i + " s=" + s + " Val: " + (myArray[i][s]));
}
// var u = 4;
s = 0;
alert(myArray[0][3]);
alert(myArray[0][4]);
alert("i=" + i + " s=" + s + " Val: " + (myArray[i][s]));
}
}
newTest()
This works for me