According to a tutorial I am reading, if you want to create a table with 5 columns and 3 rows to represent data like this...
45 4 34 99 56
3 23 99 43 2
1 1 0 43 67
...it says that you can use the following array
var table = new Array(5)
table[0] = [45, 4, 34, 99, 56];
table[1] = [3, 23, 99, 43, 2];
table[2] = [1, 1, 0, 43, 67];
But I would have expected it to be like this
var table = new Array(3)
table[0] = [45, 4, 34, 99, 56];
table[1] = [3, 23, 99, 43, 2];
table[2] = [1, 1, 0 43, 67]
If, as in the tutorial, var table is initially declared as an array with 5 elements, and then the first (table[0]), second (table[1]) and third (table[2]) are filled with the data, what happens with the other two elements that were initially set in the array with new Array(5). Why do you need to use 5?
2 Answers 2
You are correct, it sounds like the example in the tutorial is wrong.
1 Comment
That's most probably a typo on the tutorial.
new Array(5) basically creates an array object with 5 elements, initialized as undefined. JavaScript is smart enough to "resize" the array object when you had originally set it smaller than you needed. So, after you set var table = new Array(3), you can still add a tenth element to it e.g. table[9] = [1, 2, 3, 4, 5];
1 Comment
table.length is now 10 even though you've added only 6 elements.
new Array(3)in Javascript. Always usevar table = [];- pre-allocating the size doesn't really do any good.