簡體   English   中英

在 AngularJS 中更改嵌套對象值會更改所有其他值

[英]Changing nested object value in AngularJS changes all other values

考慮以下嵌套對象,它循環 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時,為什么會發生這種情況?

====更新====

實際代碼以空的預訂時間開始,如下所示:

$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函數創建不共享其內容的新對象。

有關詳細信息,請參閱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM