简体   繁体   中英

JavaScript returning a 2D array in a function

I'm trying to return an array within a function like this:

function loadMap(map) {
    if (map == 1) {
        return board = [][
[ 1, 1, 1, 1, 1, 1, 1, 190, 115, 1, 1, 1, 1, 1, 1, 2],
[ 190, 190, 190, 190, 190, 190, 190, 190, 13, 148, 148, 148, 148, 148, 121, 2],
[ 1, 520, 127, 127, 127, 127, 127, 13, 13, 148, 167, 167, 167, 148, 343, 1],
[ 1, 520, 127, 166, 166, 166, 127, 13, 13, 148, 167, 167, 167, 148, 343, 1],
[ 1, 520, 127, 166, 166, 166, 127, 13, 13, 148, 148, 148, 183, 148, 343, 1],
[ 1, 520, 364, 174, 127, 361, 127, 13, 13, 13, 13, 13, 13, 13, 13, 1],
[ 115, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 115],
[ 1, 514, 13, 13, 394, 343, 145, 220, 145, 145, 145, 13, 13, 13, 13, 1],
[ 1, 514, 13, 13, 343, 118, 145, 166, 166, 166, 145, 13, 13, 13, 13, 1],
[ 1, 514, 514, 13, 118, 118, 145, 166, 166, 166, 145, 13, 13, 13, 13, 1],
[ 1, 1, 1, 115, 1, 1, 145, 145, 145, 145, 145, 1, 1, 1, 1, 1]
];
    }
}

However that is not right. How do I fix this?

You don't give the return value a name in the function, assign the return value to a variable when you call it.

You have an extra [] in front of the array literal.

function loadMap(map) {
  if (map == 1) {
    return [
      [ ... ],
      [ ... ],
      [ ... ],
      ...
    ];
  }
}

var board = loadMap(1);
function loadMap(map) {
    if (map == 1) {
        return [
            [values],
            [values],
            [values]
        ]
    }
}

you can access them like map[x][y] :

var map = loadMap(1);

map[1][1]; //190

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM