我对数组的创建有点困惑。我有一个带有 x:y 坐标及其尺寸(网格大小)的项目列表...例如:
x: 1
y: 7
width: 2 tiles
height: 2 tiles
所以我想做的想法是创建一个“占用”的 x:y 网格数组。但是循环这些数据,因此占用的图 block 将是:
x: 1
y: 7
//
x: 2
y: 7
//
x: 1
y: 8
//
x: 2
y: 8
因为在上面的示例中,该项目是 2 x 2 block (一个正方形)。
我的对象的结构如下(如console.log(sdata);所示)
7: Array[4]
0: "1"
1: "7"
2: "2"
3: "2"
所以,是的,我正在尝试创建一个数组来存储这种网格引用。希望我解释了我想要得到的内容,但我无法弄清楚如何构造一个循环来创建数组。
最佳答案
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
关于javascript - 创建坐标网格数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10000628/