如何在javascript中使用循环创建地图?

时间:2015-05-26 10:57:14

标签: javascript dictionary

我有一个问题 - 如何用于在javascript中创建地图? 我的实际代码:

wall_array = [{x:0,y:0},{x:0,y:1},{x:0,y:2},{x:0,y:3},{x:0,y:4},{x:0,y:5},{x:0,y:6},{x:0,y:7},{x:0,y:8},{x:0,y:9},{x:0,y:10},{x:0,y:11},{x:0,y:12},{x:0,y:13},{x:0,y:14},{x:0,y:15},{x:0,y:16},{x:0,y:17},{x:0,y:18},{x:0,y:19},{x:0,y:20},{x:0,y:30},{x:0,y:31},{x:0,y:32},{x:0,y:33},{x:0,y:34},{x:0,y:35},{x:0,y:36},{x:0,y:37},{x:0,y:38},{x:0,y:39},{x:0,y:40},{x:0,y:41},{x:0,y:42},{x:0,y:43},{x:0,y:44},{x:0,y:45},{x:0,y:46},{x:0,y:47},{x:0,y:48},{x:0,y:49},{x:1,y:0},{x:2,y:0},{x:3,y:0},{x:4,y:0},{x:5,y:0},{x:6,y:0},{x:7,y:0},{x:8,y:0},{x:9,y:0},{x:10,y:0},{x:11,y:0},{x:12,y:0},{x:13,y:0},{x:14,y:0},{x:15,y:0},{x:30,y:0},{x:31,y:0},{x:32,y:0},{x:33,y:0},{x:34,y:0},{x:35,y:0},{x:36,y:0},{x:37,y:0},{x:38,y:0},{x:39,y:0},{x:40,y:0},{x:41,y:0},{x:42,y:0},{x:43,y:0},{x:44,y:0},{x:1,y:49},{x:2,y:49},{x:3,y:49},{x:4,y:49},{x:5,y:49},{x:6,y:49},{x:7,y:49},{x:8,y:49},{x:9,y:49},{x:10,y:49},{x:11,y:49},{x:12,y:49},{x:13,y:49},{x:14,y:49},{x:15,y:49},{x:30,y:49},{x:31,y:49},{x:32,y:49},{x:33,y:49},{x:34,y:49},{x:35,y:49},{x:36,y:49},{x:37,y:49},{x:38,y:49},{x:39,y:49},{x:40,y:49},{x:41,y:49},{x:42,y:49},{x:43,y:49},{x:44,y:49},{x:44,y:1},{x:44,y:2},{x:44,y:3},{x:44,y:4},{x:44,y:5},{x:44,y:6},{x:44,y:7},{x:44,y:8},{x:44,y:9},{x:44,y:10},{x:44,y:11},{x:44,y:12},{x:44,y:13},{x:44,y:14},{x:44,y:15},{x:44,y:16},{x:44,y:17},{x:44,y:18},{x:44,y:19},{x:44,y:20},{x:44,y:30},{x:44,y:31},{x:44,y:32},{x:44,y:33},{x:44,y:34},{x:44,y:35},{x:44,y:36},{x:44,y:37},{x:44,y:38},{x:44,y:39},{x:44,y:40},{x:44,y:41},{x:44,y:42},{x:44,y:43},{x:44,y:44},{x:44,y:45},{x:44,y:46},{x:44,y:47},{x:44,y:48}];

我可以写短吗? 请帮忙。

2 个答案:

答案 0 :(得分:0)

只需使用嵌套循环......

var wall_array = [];
for (var j = 0; j < 50; ++j) {
  for (var i = 0; i < 50; ++i) {
     results.push ({x : j, y : i});
  }
}

答案 1 :(得分:0)

查看数据的x和y模式,我想出了以下for循环(以及一些if逻辑)。

var wall_array = [];
var x, y;

for(x = 0; x <= 44; x++) {
    if(x == 0) {
        for (y = 0; y <= 20; y++) {
            wall_array.push({x: x, y: y});
        }

        for(y = 30; y <= 49; y++) {
            wall_array.push({x: x, y: y});
        }
    }

    if(x >= 1 && x <= 15) {
        wall_array.push({x: x, y: 0});
        wall_array.push({x: x, y: 49});
    }

    if(x >= 30 && x <= 44) {
        wall_array.push({x:x, y: 0});
        wall_array.push({x:x, y: 49});
    }

    if(x == 44) {
        for(y=1; y<=20; y++) {
            wall_array.push({x:x, y:y});            
        }

        for(y=30; y<=48; y++) {
            wall_array.push({x:x, y:y});            
        }
    }
}