[英]Assigning to array doesn't work as expected
I am trying to rotate array clockwise for example from: 我试图从例如顺时针旋转数组:
[[1,2,3],
[4,5,6],
[7,8,9]]
make: 使:
[[7,4,1],
[8,5,2],
[9,6,3]]
so I written a function for that its looks as below: 所以我为此编写了一个函数,如下所示:
function rotateImage(a) {
const arr = Array(a.length).fill(Array(a.length).fill(0));
for(let i =0; i< a.length; i++) {
for(let j = 0; j < a[i].length;j++ ){
console.log(i,j);
arr[j][a[i].length-1 - i] = a[i][j];
console.log(arr)
}
}
return arr;
}
here are logs i get: 这是我得到的日志:
0 0
[ [ 0, 0, 1 ], [ 0, 0, 1 ], [ 0, 0, 1 ] ]
0 1
[ [ 0, 0, 2 ], [ 0, 0, 2 ], [ 0, 0, 2 ] ]
0 2
[ [ 0, 0, 3 ], [ 0, 0, 3 ], [ 0, 0, 3 ] ]
1 0
[ [ 0, 4, 3 ], [ 0, 4, 3 ], [ 0, 4, 3 ] ]
1 1
[ [ 0, 5, 3 ], [ 0, 5, 3 ], [ 0, 5, 3 ] ]
1 2
[ [ 0, 6, 3 ], [ 0, 6, 3 ], [ 0, 6, 3 ] ]
2 0
[ [ 7, 6, 3 ], [ 7, 6, 3 ], [ 7, 6, 3 ] ]
2 1
[ [ 8, 6, 3 ], [ 8, 6, 3 ], [ 8, 6, 3 ] ]
2 2
[ [ 9, 6, 3 ], [ 9, 6, 3 ], [ 9, 6, 3 ] ]
so when i have i=0
and j=0
, My code should turn to something like this: 所以当我有
i=0
和j=0
,我的代码应该变成这样:
arr[0][2]= a[0][0];
// so I should get
[ [ 0, 0, 1 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
// insted of
[ [ 0, 0, 1 ], [ 0, 0, 1 ], [ 0, 0, 1 ] ]
can somebody explain for me what is going on here? 有人可以帮我解释一下这是怎么回事吗?
The problem is the way you created your output array: 问题是您创建输出数组的方式:
const arr = Array(a.length).fill(Array(a.length).fill(0));
This says "Every element of arr
should equal the result of Array(a.length).fill(0)
. That is to say, array arr
has three elements, each of which is the same object . 这说:“
arr
每个元素都应等于Array(a.length).fill(0)
。也就是说,数组arr
具有三个元素,每个元素都是同一个对象 。
Therefore, when you assign a value to arr[0][2]
, you are also assigning it to arr[1][2]
, etc. 因此,当您将值分配给
arr[0][2]
,您也将其分配给arr[1][2]
等。
You could use a loop like this to create your new matrix: 您可以使用如下循环创建新矩阵:
var arr = Array(a[0].length);
for (var i = 0; i < arr.length; i++)
arr[i] = Array(a.length).fill(0);
the problem is the output array 问题是输出数组
Solution : 解决方案:
function rotateImage(a) {
let arr = Array(a.length);
for(let i =0; i< 3; i++) {
for(let j = 0; j < a[i].length;j++ ){
if(!arr[j]) {
arr[j] = Array(a[j].length)
}
arr[j][a[i].length-1 - i] = a[i][j];
}
}
return arr;
}
This function can be written as three maps, in a one-liner: 此函数可以单行写成三个映射:
const rotateImage = a => a[0].map((_, i) => a.map(r => r[i])).map(r => r.reverse()) console.log(rotateImage([ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]))
Note that this works with non-square grids as well. 请注意,这也适用于非正方形网格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.