问题描述
我有这个代码.我什至用 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.
fill()
方法用静态值填充数组从开始索引到结束索引的所有元素.
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)
这篇关于为什么这两个空数组的填充方式不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!