JavaScript在函数中返回2D数组

时间:2012-04-21 02:12:57

标签: javascript

我正在尝试在这样的函数中返回一个数组:

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]
];
    }
}

然而这是不对的。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:5)

您不会在函数中为返回值指定名称,在调用时将返回值赋给变量。

在数组文字前面有一个额外的[]

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

var board = loadMap(1);

答案 1 :(得分:0)

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

您可以像map[x][y]

那样访问它们
var map = loadMap(1);

map[1][1]; //190