我有一个像这样的多维数组:
var map = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]];
然后,我有一些函数可以根据一些变量在两个维度上“调整”数组的大小。我就是这样做的:
function resizeArr(arr, rows, rowsDiff, cols, colsDiff) {
var arrLength = arr.length;
if (colsDiff > 0) {
i=0;
while (i<arrLength) {
j=0;
while (j<colsDiff) {
arr[i].push(0);
j++
}
i++
}
}
if (colsDiff < 0) {
i=0;
while (i<arrLength) {
j=0;
colsDiffAbs = Math.abs(colsDiff);
while (j<colsDiffAbs) {
arr[i].pop();
j++
}
i++
}
}
if (rowsDiff > 0) {
fullColsArr = makeArrayOf(0, cols);
i=0;
while (i<rowsDiff) {
arr.push(fullColsArr);
i++
}
}
if (rowsDiff < 0) {
rowsDiffAbs = Math.abs(rowsDiff);
i=0;
while (i<rowsDiffAbs) {
arr.pop();
i++
}
}
return arr;
}
基本上,使用这 4 个 if 语句,我会根据 rowsDiff/colsDiff 变量是正数还是负数,弹出一些值或推送一些新值(零)。
我的问题是,当我将数组的大小从 map[4][4] 的最大值调整为 map[9][9] 时,看起来一切正常,因为我得到:
[[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0]]
作为我的新数组,看起来不错。但是,当我尝试将特定值分配给 map[9][9] 时,它会填充每个新数组的最后一个值,如下所示:
[[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,14],[0,0,0,0,0,0,0,0,0,14],[0,0,0,0,0,0,0,0,0,14],[0,0,0,0,0,0,0,0,0,14],[0,0,0,0,0,0,0,0,0,14]]
如果我尝试为倒数第二个值(map[9][8])分配一个值,它也会填充所有其他值的倒数第二个值。
但是当我为数组的原始部分赋值时,它可以正常工作。我在这里做错了什么?
我已尽力解释它 - 请随时询问更多细节。