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.