javascript - 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(最后一个索引)
解决方案
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});
}
推荐阅读
- postgresql - 无法使用 JDBC 驱动程序连接到远程 PostgresSQL 服务器
- javascript - 如何在 javascript 中执行命令将文件上传到应用程序?
- android - overridePendingTransition 在 API 23 中使屏幕变黑,但在 API 29 中运行良好
- reactjs - 如何优雅地处理由 dangerouslySetInnerHTML 引起的 react-dom 错误?
- indexing - 在 APL 中使用嵌套向量进行索引
- python - 在python的另一个模块中访问一个模块的函数的局部变量
- javascript - 如何更新会话存储中项目的单个值
- android - 错误:Android Gradle 插件仅支持 Kotlin Gradle 插件版本 1.3.10 及更高版本
- python - 如何在熊猫行中找到一个字符串,它应该是一个浮点数?
- html - flex 容器无法正常下车