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
for (var i = 0; i < $('#rows').val(); i++) {
new_array[i][0] = i;
}
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.
var new_array = [];
for (var i=0; i<5; i++) {
// create and add a new subarray explicitly:
new_array[i] = [];
// add a value to that subarray:
new_array[i][0] = i;
// add other values to the subarray:
new_array[i][1] = "";
}
// new_array now looks like this:
[[0, ""], [1, ""], [2, ""], [3, ""], [4, ""]]
// You might shorten the whole code by using stuffed literals for the sub arrays:
for (var new_array=[], i=0; i<5; i++)
new_array[i] = [i, ""];