[英]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.