为什么在这种情况下默认数组已被突变?

时间:2019-03-15 06:49:41

标签: javascript

let points = [{x:1,y:2},{x:2,y:2}];
let centroidsPoints = [1,2].map(() => []);
console.log(centroidsPoints); // => [[],[]]
let centroidsPointsCopy = [...centroidsPoints]; //copy array
points.forEach(point => {
  centroidsPointsCopy[0].push(point);
});
console.log(centroidsPointsCopy); // => [[{x:1,y:2},{x:2,y:2}],[]]
console.log(centroidsPoints); // => [[{x:1,y:2},{x:2,y:2}],[]] but expected [[],[]]

为什么我没有得到预期的行为,因为我用复制了默认数组

[...centroidPoints]

对不起,如果重复,我只能找到“ array1 = array2”副本的答案;

0 个答案:

没有答案