创建坐标的网格数组

时间:2012-04-03 20:11:27

标签: javascript

我对我的阵列创建感到困惑。我有一个带有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"

所以是的,我试图制作一个数组来存储这种网格参考。希望我解释了我想要的内容,但我无法弄清楚如何构造一个循环来创建数组。

3 个答案:

答案 0 :(得分: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属性,以使其更易于理解。

答案 1 :(得分: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

答案 2 :(得分: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} ]
]