0

I have this code:

testArray = new Array(2);
for (var i = 0; i < testArray.length; i++) {
    testArray[i] = new Array(2);
    for (var j = 0; j < testArray[i].length; j++) {
        testArray[i][j] = new Array(2);
        for (var k = 0; k < testArray[i][j].length; k++) {
            testArray[i][j][k] = new Object;

            testArray[i][j][k].x = function () {
                return i;
            }
        }
    }
}

And as you can see, I create an array, inside an array, inside an array (a 3D array). At the end I have a function that is supposed to give me the value of the first array of this 3d array. Here an example:

testArray[0][1][0].x -> 0
testArray[0][0][1].x -> 0
testArray[1][0][0].x -> 1

But when I call the function testArray[1][0][0].x it always returns 2. I do not know where I have made an error. Could someone help me please?

Some guy
  • 1
  • 1
  • `testArray[1][0][0].x` is a method . so you should do like this `testArray[1][0][0].x()` – Mahi Nov 13 '16 at 15:53
  • 1
    Because `i` will be at max value at the time you call the function. You need a closure as per the duplicate link above – charlietfl Nov 13 '16 at 15:55

0 Answers0