首页 > 解决方案 > JS 对象数组做奇怪的事情

问题描述

const allocation = [
   {partner: 3},
   {partner: 1},
   {partner: 2},
   {partner: 0},
   {partner: 4}
];

const rightallocation = new Array(5);
rightallocation.fill({number: 1});

for (let i = 0; i < allocation.length; i++) {

   const rightIndex = allocation[i].partner;
   rightallocation[rightIndex].number = i;


   console.log("Filling "+ (i) + " into rightallocation["+ (allocation[i].partner)+"]");
   console.log(rightallocation[allocation[i].partner]);
}

console.log(rightallocation); 

此代码应采用数组“分配”并对其进行镜像。例如分配[0] = 3,所以正确分配[3] = 0。我在for中的所有日志都给出了正确的数字,但我得到一个充满数字的数组:4(最后一个索引)

这是控制台日志

标签: javascriptarraysjavascript-objects

解决方案


rightallocation这是因为同一个对象在您的数组中被引用了 5 次。

所以这一行:

rightallocation[rightIndex].number = i;

每次都在更改数组中.number所有元素,因为所有元素都是对您在执行此操作时填充数组的单个{number : 1}对象的引用:rightallocation

rightallocation.fill({number: 1})

尝试更改这些行:

const rightallocation = new Array(5);
rightallocation.fill({number: 1});

对于这样的事情:

const rightallocation = new Array(5).fill().map(u => ({number: 1}));

为了使发生的事情更清楚,请尝试用像这样更明确的内容填充您的数组。这将确保始终创建一个新对象,并且您的数组中最终有五个不同的对象:

const rightallocation = [];

for (let i=0; i < 5; i++) {
  rightallocation.push({number: 1});
}

推荐阅读