从其他2D数组Javascript部分创建2D数组 [英] Creating 2d array from section of other 2d array Javascript
问题描述
我正在尝试剪切由 x,y
和 w,h
指定的2d数组的一部分.我要剪切的数组的一个例子是
I am trying to cut a section of a 2d array specified by x, y
and w, h
.
an example of an array I'm trying to cut would be
var arr = [
['0', '1', 'd', 'a', '1', '1'],
['0', 's', '0', 'f', 's', 'g'],
['b', 'x', 'e', '0', 'v', 'a'],
['a', 'e', 'n', '0', 'z', 'm'],
['b', 'x', 'e', '0', 'v', 'a'],
];
所以如果我叫 snapshot(2,1,4,4,2)
我想要的输出是
so if i called snapshot(2, 1, 4, 2)
my desired output would be
var retarr = [
['0', 'f', 's', 'g'],
['e', '0', 'v', 'a'],
]
到目前为止,我只有在我的 W idth和 H 8个相等.
So far I can cut the section and return a new array successfully but only if my Width and Height are equal.
snapshot(x, y, w, h){
var retgrid = new Grid(w, h);
var startX = x;
var startY = y;
var endX = x + w;
var endY = y + h;
console.log(`x: ${x} y: ${y}`)
console.log(`w: ${w} h: ${h}`)
for(var i = startY; i < endY; i++){
for(var j = startX; j < endX; j++){
// console.log(retgrid)
retgrid[j - startX][i - startY] = this.grid[j][i]
}
}
console.log(retgrid)
return retgrid;
}
不断发生的错误是 game.js:316未捕获的TypeError:无法设置未定义的属性"-1"
我已经有一段时间了.我知道这可能只是一些简单的逻辑错误,但由于某些原因,我无法查明.有人可以发现我在做什么错吗?
I have been going at this for a while now. I know it's probably just some simple logic error but for some reason, I just cannot pinpoint it. Can anyone find what I'm doing wrong?
推荐答案
Using .slice
allows you to pull out bits of arrays. First pull out the rows at Y -> Y + H. Next, using map() to go through each of those to slice each into the columns from X -> X + W.
您需要添加安全保护措施,以免超出数组的大小或形状.
You'll need to add safe guards to avoid exceeding the size or shape of the arrays.
var arr = [
['0', '1', 'd', 'a', '1', '1'],
['0', 's', '0', 'f', 's', 'g'],
['b', 'x', 'e', '0', 'v', 'a'],
['a', 'e', 'n', '0', 'z', 'm'],
['b', 'x', 'e', '0', 'v', 'a'],
];
console.log(snapshot(2, 1, 4, 2));
function snapshot(x, y, w, h) {
return arr.slice(y, y + h).map(a => a.slice(x, x + w))
}
这篇关于从其他2D数组Javascript部分创建2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!