考虑以下嵌套对象,它循环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;
当$rootScope.bookings_times_list[0]的密钥在第一周明显设置为0时,为什么会发生这种情况?
====UPDATE====
实际代码以空预订时间开始,如下所示:
$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循环似乎是造成问题的原因。剪接是否影响对象的初始化方式?
===UPDATE===
我也注意到问题不在于剪接。因为从
$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循环中,仍然会产生相同的问题。
发布于 2019-12-01 15:39:16
使用angular.copy
.splice(index, 1, angular.copy(monday));angular.copy函数创建不共享其内容的新对象。
有关详细信息,请参阅
https://stackoverflow.com/questions/59126239
复制相似问题