为什么我的数组元素被这个声明改变了?

问题描述 投票:0回答:2

Javascript代码:

const bigArray2 = [
    [1, 2, 3],
    [2, 4, 6],
    [3, 6, 9],
  ];
  
  //creates single-layer array containing all elements of every array within bigArray2
  const combinedArray = bigArray2.reduce((accumulated, current) => {
    for (element of current) {
      accumulated.push(element);
    }
    return accumulated;
  });
  

  console.log(combinedArray);
  // outputs [ 1, 2, 3, 2, 4, 6, 3, 6, 9 ] as intended
  

  console.log(bigArray2); 
  // outputs [ [ 1, 2, 3, 2, 4, 6, 3, 6, 9 ], [ 2, 4, 6 ], [ 3, 6, 9 ] ]

不知何故,bigArray2[0]被分配了combinedArray的值。如何以及为何? .reduce() 不应该改变原始数组

javascript reduce
2个回答
0
投票

您没有将初始值传递给您的

reduce()
函数。

更正代码:

const bigArray2 = [
    [1, 2, 3],
    [2, 4, 6],
    [3, 6, 9],
  ];
  
  //creates single-layer array containing all elements of every array within bigArray2
  const combinedArray = bigArray2.reduce((accumulated, current) => {
    for (element of current) {
      accumulated.push(element);
    }
    return accumulated;
  }, []);
  

  console.log(combinedArray);
  // outputs [ 1, 2, 3, 2, 4, 6, 3, 6, 9 ] as intended
  

  console.log(bigArray2); 
  // outputs [ [ 1, 2, 3, 2, 4, 6, 3, 6, 9 ], [ 2, 4, 6 ], [ 3, 6, 9 ] ]


0
投票

.reduce() 不应更改原始数组

.reduce()
完全有可能更改原始数组,这更多地与您在回调中所做的确定原始数组是否更改有关。

在您的情况下,由于您将第二个参数提交给

.reduce()
(即:初始值),
.reduce()
将首先调用您的回调,并将累加器设置为数组中的第一项。在本例中,这是对第一个元素数组
[1, 2, 3]
的引用。因此,由于您不断从
.reduce()
回调返回相同的数组引用值,因此最终所有值都被推送到第一个数组。

要解决此问题,您可以提供一个空数组作为初始值:

const bigArray2 = [
  [1, 2, 3],
  [2, 4, 6],
  [3, 6, 9],
];

//creates single-layer array containing all elements of every array within bigArray2
const combinedArray = bigArray2.reduce((accumulated, current) => {
  //   v--- declare this as const to avoid making it a global
  for (const element of current) {
    accumulated.push(element);
  }
  return accumulated;
}, []); // <--- pass an initial array


console.log(combinedArray);
// outputs [ 1, 2, 3, 2, 4, 6, 3, 6, 9 ] as intended


console.log(bigArray2);

© www.soinside.com 2019 - 2024. All rights reserved.