问题描述
我有这个代码.我什至把console.logs进行调试.但是我真的不明白他们为什么以不同的方式表现.为什么result1数组用最后一个数组值填充所有内部数组?
I have this code. I even put console.logs to debug it. But I really don't understand why are they behaving in a different way. Why do the result1 array fill all the internal arrays with the last array values?
var myMatrix = [
[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11],
[12, 13, 14, 15]
];
function rotateMatrixClockwise(matrix) {
var long = matrix.length;
var result1 = new Array(long).fill([]);
var result2 = [ [], [], [], [] ];
console.log("Empty result1:");
console.log(result1);
console.log("Empty result2:");
console.log(result2);
for (var row = 0; row < long; row++) {
for (var col = 0; col < long; col++) {
result1[row][col] = matrix[long - col - 1][row];
result2[row][col] = matrix[long - col - 1][row];
}
}
console.log("Result1:");
console.log(result1);
console.log("Result2:");
console.log(result2);
}
rotateMatrixClockwise(myMatrix);
推荐答案
您正在使用与数组中相同的对象引用填充数组
You are filling the array with the same object reference of the array in
var result1 = new Array(long).fill([]);
// ^^ same array for all elements
以后任何分配都将在同一数组中进行.
Any assignment later takes place in the same array.
在工作版本中,
var result2 = [[], [], [], []];
// ^^ ^^ ^^ ^^ four different arrays
您采用了四个不同的数组,它们没有引用同一数组.
you takes four different arrays, which have no reference to the same array.
Array.fill
声明静态行为,而在使用Javascript时,对象是通过引用移交的.
The reference for Array.fill
states the static behavior, and while Javascript, objects are handed over by reference.
var myMatrix = [
[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11],
[12, 13, 14, 15]
];
function rotateMatrixClockwise(matrix) {
var array = [];
var long = matrix.length;
var result1 = new Array(long).fill(array);
var result2 = [[], [], [], []];
console.log("Empty result1:");
console.log(result1);
console.log("Empty result2:");
console.log(result2);
for (var row = 0; row < long; row++) {
for (var col = 0; col < long; col++) {
result1[row][col] = matrix[long - col - 1][row];
result2[row][col] = matrix[long - col - 1][row];
}
}
console.log("Result1:");
console.log(result1);
console.log("Result2:");
console.log(result2);
console.log('array', array);
}
rotateMatrixClockwise(myMatrix)
这篇关于为什么这两个空数组的填充方式不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!