I have the following code in which I am trying to populate a two dimensional array (myArray) using the values from an object (myObject) but I am getting the error mentioned in the post title. The error is tied to the 4th line.
var myArray = [];
var j = 0;
for (var i in myObject) {
myArray[j][0] = i;
myArray[j][1] = myObject[i];
myArray[j][2] = myObject[i] * 2;
/* alert(myArray[j][0] + ', ' + myArray[j][1] + ', ' + myArray[j][2]) */
j++;
}
When I test with alert(), only the first element of myArray is displayed, the rest seems not being defined and I donât know whatâs wrong.
Sorry for the multiple replies, but I believe if we figure out what is wrong in the following code, the issue will be solved:
var temp = [[]];
for (var i = 0; i < 5; i++) {
temp[i][0] = 'test';
alert(temp[i][0]);
}
The above alerts âtestâ only one time, whereas I would expect it to display for 5 times. And the Console gives âTypeError: temp[i] is undefinedâ error.
[quote=âJames_Hibbard, post:7, topic:190412, full:trueâ]Should the third element in each array be the result of calling func() and passing it the previous element as an argument?
[/quote]
Hi, yes.
If you could please check my last reply before yours, you may notice what is wrong with my multidimensional array. Canât see the issue myself.
Well, trying to collect bits of correct information on the web is sort of a tough task. I did a search for âjavascript define multidimensional arrayâ and some of the results suggested that declaration I had used. Even the first reply to this post did so.
When you first start myArray = [] then myArray is an empty array. That means myArray[0] is empty (undefined), myArray[3] is undefined, myArray[10] is undefined, and so on. If you tried to access myArray[0][0], then youâre assuming myArray[0] is an array, but itâs not, itâs still undefined. myArray[0] = [i] works because instead of trying to access the 0-th element of a non-array, now youâre actually assigning the array.