首页 > 解决方案 > 更改 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_selected1更改为如下所示会将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 循环中仍然产生同样的问题。

标签: javascriptangularjs

解决方案


使用angular.copy

 .splice(index, 1, angular.copy(monday));

angular.copy函数创建不共享其内容的新对象。

有关详细信息,请参阅


推荐阅读