[英]Why making changes to copy of array , affects to original array?
用戶登錄后,我會按權限過濾菜單數組。
我正在生成 static 菜單,然后將數組副本提供給過濾器。
constructor(public menu: MenuService, public permissionService: PermissionService) {
console.log(menu.getMenu()) // this changes after filtering below
this.menuItems = this.permissionService.filterMenuByTopic([...menu.getMenu()]); // here I'm using a copy
}
為什么會這樣? 如果我使用了擴展運算符並且不使用原始數組[...menu.getMenu()]
。
只有當我刷新頁面menu.getMenu()
返回原始值
更新 1
回答評論,這里是 getMenu() 函數
import { Injectable } from '@angular/core';
@Injectable()
export class MenuService {
menuItems: Array<any>;
constructor() {
this.menuItems = [];
}
addMenu(items: Array<{
text: string,
heading?: boolean,
link?: string, // internal route links
elink?: string, // used only for external links
target?: string, // anchor target="_blank|_self|_parent|_top|framename"
icon?: string,
alert?: string,
submenu?: Array<any>
}>) {
items.forEach((item) => {
this.menuItems.push(item);
});
}
getMenu() {
return this.menuItems;
}
}
擴展運算符創建一個淺拷貝。 如果菜單的內容是對象,那么更改副本數組中的這些對象將更改原始數組中的那些對象(或者從技術上講,這兩個引用是針對同一個對象的):
const obj1 = { val: 1 } const obj2 = { val: 2 } const obj3 = { val: 3 } const arr = [obj1, obj2, obj3] // creating a copy with the spread operator const copy = [...arr] // changing the second element in the copy copy[1].val = 22 // the element in the original array is changed too console.log(arr)
感謝伊萬的評論
我通過以下方式進行了深度克隆
const cloned = menu.getMenu().map(x => Object.assign({}, x));
console.log('cloned ', cloned)
this.menuItems = this.permissionService.filterMenuByTopic(cloned);
我在這里找到的答案之一鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.