I want to create a 2-dimensional array with an index-number in each first element.
EDIT:
thx a lot so far..
@carl: I did so much function creation just to show the kind of tries I did..
jonhopkins idea gave rise to this:
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));
});
try do this
The definitions of 'i' can be done in the beginning of the main function, because the for loop has not closure. So, when the loop ends the 'i' var is still available. you can read this book http://shop.oreilly.com/product/9780596517748.do
There are no two-dimensional arrays in JavaScript, there are just array objects that may contain other array objects (but also anything else).
new Array(new Array());
does not what you expect. Btw, you might use an empty-array-literal[]
instead of calling the constructor explicitly.