2012-04-03 38 views
0

我有点困惑与我的数组创建。我有X的项目清单:y坐标坐标以及它们的尺寸(网格大小)...例如:创建协调网格阵列

x: 1 
y: 7 
width: 2 tiles 
height: 2 tiles 

这样的想法我尝试做的是创造x的数组:Y网格那是“被占领”的。但这样的循环数据,以便被占领瓦片会那里为:

x: 1 
y: 7 
// 
x: 2 
y: 7 
// 
x: 1 
y: 8 
// 
x: 2 
y: 8 

由于在上述示例中的产品2乘2瓦(正方形)。

我对象的结构是这样的(在执行console.log(SDATA)所示;)

7: Array[4] 
0: "1" 
1: "7" 
2: "2" 
3: "2" 

所以是我尝试做一个数组来存储这种网格reference..Hope的我解释什么,我试图去,但我不能解决如何构建一个循环来创建数组。

+0

你做了什么? – Alexander 2012-04-03 20:14:06

+0

最后一个代码块中的“对象结构”没有任何意义。为什么数字字符串?左手属性与右手值有什么关系?为什么7是一个数组? – mikerobi 2012-04-03 20:15:59

+0

看看这个。它可能有帮助:http://stackoverflow.com/questions/2529865/javascript-multidimensional-array – 2012-04-03 20:19:49

回答

1

http://jsfiddle.net/rlemon/JeeV2/这里是你如何能生产这种类型的示例'网格'占用资料..

var chords = [ // instead of arrays we'll use objects.. they're nicer. 
    { 
    x: 1, 
    y: 7, 
    h: 2, // height 
    w: 2}, // width 
{ // ohh look a second plot point. 
    x: 4, 
    y: 1, 
    h: 3, 
    w: 2}, 
]; 

var occupied = { // will be your cells points occupied 
    x: [], 
    y: []  
}; 
chords.forEach(function(chord) { // now lets loop the chords and produce the occupied array 
    occupied.x.push(chord.x); 
    occupied.x.push(chord.x + (chord.w-1)); // expand the width of the cell - initial point 
    occupied.y.push(chord.y); 
    occupied.y.push(chord.y + (chord.h-1)); // expand the height of the cell - initial point 
}); 
console.log(occupied); 
// outputs 
​Object 
    x: Array[4] 
     0: 1 
     1: 2 
     2: 4 
     3: 5 

    y: Array[4] 
     0: 7 
     1: 8 
     2: 1 
     3: 3 
+0

如果我想知道y:8是否被占用,我将如何检查,因为我不知道它是在阵列位置[1]? – Sir 2012-04-03 20:50:56

+0

当然......'如果占领.y.indexOf(8)'http://jsfiddle.net/rlemon/JeeV2/1/ – rlemon 2012-04-03 20:54:40

1

生成的outputArray数组是以{ x: value, y: value}的形式表示的一组对象。

var inputArray = [ [1,7,2,2], ... ]; 
var outputArray = []; 
for(var i = 0; i < inputArray.length; i++) { 
    var item = { 
     x: inputArray[i][0], 
     y: inputArray[i][1], 
     width: inputArray[i][2], 
     height: inputArray[i][3] 
    }; 
    for(var xx = 0; xx < item.width; xx++) { 
     for(var yy = 0; yy < item.height; yy++) {   
      outputArray.push({ 
       x: item.x + xx, 
       y: item.y + yy 
      }); 
     } 
    } 
} 

我加了xywidthheight属性,使其更容易理解。

0
function range(a, b) { 
    /* 
     range(5) -> [0,1,2,3,4] 
     range(1,4) -> [1,2,3] 
    */ 
    if (b===undefined) 
     var start=0, stop=a; 
    else 
     var start=a, stop=b; 

    var R = []; 
    for(var i=start; i<stop; i++) 
     R.push(i); 
    return R; 
} 

那么它是一个双内胆:

range(x, x+width).map(function(x) { 
    return range(y, y+height).map(function(y) { 
     return {x:x, y:y}; // anything you'd like 
    }) 
}) 

结果(通过JSON.stringify获得):

[ 
    [ {"x":1,"y":7}, {"x":1,"y":8} ], 
    [ {"x":2,"y":7}, {"x":2,"y":8} ] 
]