Alpha Centauri A B
Alpha Centauri A B

Reputation: 143

Using the Array methods with nested (multidimensional) arrays?

I am having problems when using Array methods with nested arrays.

var map = [
        ["Blank", "Blank", "Blank"],
        ["Blank", "Player", "Blank"],
        ["Blank", "Blank", "Blank"]
];

for (i=0; i<map.length; i++) {
        for (j=0; j<map[i].length; j++) {
            var playerY = map[i][j].indexOf("Player");
        }
}

console.log(playerY);

This will always log -1 which is I know an error. Although I think my issue is with using nested arrays. It could also be a problem with the way I am using .indexOf(), or the way I am looping through the arrays. Thank you for helping. Any advise would be appreciated! :)

EDIT: Thank you for all the help. I ended up changing things a lot and not using the .indexOf() method all together. Here is what I ended up doing.

var map = [
        ["Blank", "Blank", "Blank"],
        ["Blank", "Player", "Blank"],
        ["Blank", "Blank", "Blank"]
];

for (x = 0; x < map.length; x++) {
    for (y = 0; y < map[x].length; y++) {
        if (map[x][y] == "Player") {
            console.log("(" + x.toString() + ", " + y.toString() + ")");
        }
    }
}

Upvotes: 1

Views: 111

Answers (2)

DarkAjax
DarkAjax

Reputation: 16223

Your problem is that playerY is evaluated for each of map elements, and since the last one doesn't match "Player", your final result is -1.

Basically in this case is as if you were testing this:

var playerY = map[2][2].indexOf("Player");

And since that element is "Blank", it'll return -1

Upvotes: 0

David G
David G

Reputation: 96810

The loop doesn't stop when indexOf finds "Player" inside the nested array. It will continue to loop, thus overwriting the value of playerY with each iteration. To fix this, we must break when indexOf has found the string:

for (i = 0; i < map.length; i++) {
    for (j = 0; j < map[i].length; j++) {
        var playerY = map[i][j].indexOf("Player");

        if (playerY > -1) break; // We have found "Player"
    }
}

Upvotes: 6

Related Questions