javascript - 更改 AngularJS 中的嵌套对象值会更改所有其他值
问题描述
考虑以下嵌套对象,该对象循环 10 次以生成具有 10 周计划的对象,每个星期一的给定时间:
$rootScope.bookings_times_list = [];
for (i = 0; i < 10; i++) {
$rootScope.bookings_times_list.push({
week: i,
schedule: [{
booking_day: "Monday",
booking_times: [{
"booking_start_time": "00:15",
"booking_end_time": "01:00",
"booking_selected": "",
"booking_selected_date": "",
"booking_time": "30 Nov 2019 07:35hrs"
}]
}]
});
}
问题在于,将booking_selected
值1
更改为如下所示会将booking_selected
每周所有键的值更改为1
:
$rootScope.bookings_times_list[0].schedule[0].booking_times[0].booking_selected = 1;
为什么会发生这种情况,当 key for$rootScope.bookings_times_list[0]
明确设置0
为仅第一周?
====更新====
实际代码以空预订时间开始,如下所示:
$rootScope.bookings_times_list = [];
for (i = 0; i < 10; i++) {
$rootScope.bookings_times_list.push({
week: i,
schedule: [{
booking_day: "Monday",
booking_times: []
}]
});
}
随后是另一个for
循环,该循环拼接星期一并添加预订中可用的实际时间表:
for (a = 0; a < $rootScope.bookings_times_list.length; a++) {
for (y = 0; y < $rootScope.bookings_times_list[a].schedule.length; y++) {
if($rootScope.business_bookings[$rootScope.bookings_index].booking_times[y]){
var index = $rootScope.bookings_times_list[a].schedule.findIndex(x => x.booking_day === $rootScope.business_bookings[$rootScope.bookings_index].booking_times[y].booking_day);
if(index >= 0){
$rootScope.bookings_times_list[a].schedule.splice(index, 1, $rootScope.business_bookings[$rootScope.bookings_index].booking_times[y]);
}
}
}
}
看来第二个for
循环是问题的原因。拼接是否影响对象的初始化方式?
===更新===
我也刚刚注意到问题不在于接头。因为从改变
$rootScope.bookings_times_list[a].schedule.splice(index, 1, $rootScope.business_directory_records[$rootScope.index].business_bookings[$rootScope.bookings_index].booking_times[y]);
至
$rootScope.bookings_times_list[a].schedule[index] = $rootScope.business_directory_records[$rootScope.index].business_bookings[$rootScope.bookings_index].booking_times[y]
在第二个 for 循环中仍然产生同样的问题。
解决方案
使用angular.copy
:
.splice(index, 1, angular.copy(monday));
该angular.copy
函数创建不共享其内容的新对象。
有关详细信息,请参阅
推荐阅读
- r - 使用 Plotly 创建热图;改变颜色
- java - 仅在通过 JAX-RS 调用时出现休眠错误
- android - AdapterList 中的 IndexOutOfBoundsException
- ubuntu - xvda1 是否占用了我在 ec2 上的所有磁盘空间
- angular - 角 9 | 无法绑定到“加载”,因为它不是“img”的已知属性
- acumatica - 使用 Endpoint Rest API 更新 PUT 请求上的 Note System 字段
- c# - 如何从公钥字节数组创建 CX509PublicKey 对象
- reactjs - 如何在启用 react-redux 和 eslint (react-hooks/exhaustive-deps) 规则的情况下防止在 useEffect() 钩子中无限循环获取数据
- azure - 使用 keyvault 中的证书访问其他租户中的多租户应用程序
- sql - 根据另一列的值提取一列的所有行(SQL 查询)