数组和由该数组中的元素分配的变量之间的奇怪依赖关系

Weird dependencies between array and a variable that is assigned by an element from that array

当更改从数组元素分配的变量时,数组中的特定元素会随变量而变化。但是,代码中没有要更改的数组。

在代码中数组是一个对象数组,变量在函数randomCentroid(质心)中声明和赋值,该函数在initializeCentroid中被调用。

该代码用于生成关于k-means聚类的随机质心,特此代码:

//Return random centroid points with coloring
let randomCentroid = (fill) => {
  let r = Math.floor(Math.random()*points.length);
  let centroid = points[r];

  //points.splice(r, 1);
  centroid.fill = fill;
  return centroid;
}

//Gives distinct coloring to all centroid points
let initializeCentroids = (num) => {
  let allCentroids = [];
  for (let i = 0; i < num; i++) {
    let color = colors(i);
    let centroid = randomCentroid(color);
    centroid.id = 'centroid' + '-' + i;
    allCentroids.push(centroid);
  }
  return allCentroids;
}

//same for const.
let points = [{}, {}, {}, {}, {}],
  colors = d3.scaleOrdinal(d3.schemeCategory10);

initializeCentroids(3);

console.log(points);

控制台:

index.js:29

(5) [{...}, {...}, {...}, {...}, {...}]

0: {填充: "#2ca02c", id: "centroid-2"}

1:{}

2: {填充: "#ff7f0e", id: "centroid-1"}

3:{填充:“#1f77b4”,编号:"centroid-0"}

4:{}

长度:5

原型:数组(0)

如何去除由数组赋值的对象组成的变量与数组之间的依赖关系?

这部分:

let centroid = points[r]

正在获取对点数组中对象的引用

当更改 centriod 时,您也会更改数组中的对象。