I want to create a 2-dimensional array with an index-number in each first element.
(my previous question brought me to this point >)
this works:
$('#create_indexed_array').click(function() {
var new_array = [[9,9],[9,9],[9,9],[9,9],[9,9]];
for (var i = 0; i < 5; i++) {
new_array[i][0] = i;
}
alert(JSON.stringify(new_array));
});
BUT this works not:
$('#create_indexed_array').click(function() {
var new_array = new Array(new Array());
for (var i = 0; i < 2; i++) {
new_array[0][i] = ""; // create cols
}
for (var i = 1; i < 5; i++) {
new_array[i] = new_array[0]; // create rows
}
for (var i = 0; i < 5; i++) {
new_array[i][0] = i; // set index
}
alert(JSON.stringify(new_array));
});
EDIT:
my final working version (so far):
var myArray = [];
var rows = 5;
var cols = 2;
for (var i = 0; i < rows; i++) {
myArray [i] = [];
for (var j = 0; j < cols; j++) {
if (j==0) myArray [i][j] = i;
else myArray [i][j] = '';
}
}
alert(JSON.stringify(myArray));
(r) mostly by jfriend 😉
still don’t know why it isn’t possible to declare the 2D array at the beginning with: myArray = [[]]
Following your current pattern, it will work like this:
Working demo: http://jsfiddle.net/jfriend00/vJDPp/
One thing you have to remember is that assigning an array assigns a reference to that array, not a copy so if you want each element of the array to be different, you have to physically make a copy of the first row to put in the subsequent rows. I’d also recommend changing the name of
new_arraybecause that sounds so much like a function name that it makes the code confusing to read to someone who doens’t know it.If you’re just trying to initialize a 2D array to all 9’s like in your first code example, then this would be much simpler:
Or a function version: