为什么这两个空数组的填充方式不同? [英] Why are this two empty arrays of arrays being filled differently?

查看:284
本文介绍了为什么这两个空数组的填充方式不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码.我什至把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() 方法使用静态值填充从开始索引到结束索引的数组的所有元素.

The fill() method fills all the elements of an array from a start index to an end index with a static value.

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)

这篇关于为什么这两个空数组的填充方式不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆