arrays - 当我在 forEach 循环中重新分配属性时,为什么我的对象没有改变?
问题描述
我正在从 http 后端的 RX/JS 调用中获取对象数组。它返回一个我正在尝试使用的对象。我正在使用 for 循环对此对象进行更改(在此示例中,我正在尝试,.forEach
因为我尝试了许多不同的东西,但它们似乎都不起作用。
当我运行代码时,我遇到了一个非常奇怪的问题。如果我返回属性的值,我会得到新值(即correctionQueued
返回为 true 等),但在下一行,当我返回对象时,这些相同的值与原始值相同(correctionQueued
=== false等)但是,correctionStatus
(从http的原始对象上不存在)设置得很好。
我不明白如何
array[index].correctionQueued
返回 true,但
array[index]
返回一个correctionQueued
为 false 的对象。
checklistCopy
循环之后,原始数组forEach
(correctionStatus
我尝试过使用 for of、for in 和 .forEach。我使用索引来更改原始数组,结果始终相同。预先存在的属性不会改变,会添加新的属性。我什至尝试处理对象的副本,以防从 rxjs 返回的对象有什么特别之处,但无济于事。
checklistCopy.forEach((checklistItem, index, array) => {
if (checklistItem.crCode.isirName === correctionSetItem) {
array[index].correctionQueued = true;
array[index].correctionValue = mostRecentCorrection.correctionValue;
array[index].correctionStatus = mostRecentCorrection.status;
console.log(array[index].correctionQueued, array[index].correctionValue, array[index].correctionStatus);
console.log(array[index]);
}
}
);
我没有收到错误,但我得到..
原始对象是:
correctionQueued: false;
correctionValue: JAAMES;
--
console.log(array[index].correctionQueued, array[index].correctionValue, array[index].correctionStatus);
true JAMES SENT
但是当我打印整个对象时:
console.log(array[index]);
correctionQueued: false;
correctionValue: JAAMES;
correctionStatus: "SENT'; <-- This is set correctly but does not exist on original object.
解决方案
您的输出对我来说也没有意义,但清理您的代码可能会对您有所帮助。试试这个:
checklistCopy.forEach(checklistItem => {
checklistItem.correctionQueued = checklistItem.crCode.isirName === correctionSetItem;
if (checklistItem.correctionQueued) {
checklistItem.correctionValue = mostRecentCorrection.correctionValue;
checklistItem.correctionStatus = mostRecentCorrection.status;
console.log('checklistItem', checklistItem)
}
}
);
推荐阅读
- sql - SQL查询条件在where
- flutter - 在关闭并重新打开它后让 gif 从头开始
- java - JPA 实体到 DTO 映射创建深拷贝
- sql - 获取财政年度查询中的动态日期范围的逻辑
- huggingface-transformers - 来自 pytorch_transformers ModuleNotFoundError:没有名为“utils”的模块
- input - 如何为音乐教育平台创建节奏敲击输入
- github - 如何在 GitHub Actions 中使用 env 文件?
- c++ - 使用 Makefile 中的头文件编译 Pybind(不使用 cmake)
- spring-boot - Spring Boot 微服务中的 JWT 安全性
- entity-framework - EF Core 3.0 1:0 与fluent的关系