絕地無雙
2024-01-18 14:36:48
一旦用戶登錄,我就通過權限過濾菜單數組。我生成靜態菜單,然后將數組的副本提供給過濾器。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()返回原始值UPD 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; }}
2 回答

倚天杖
TA貢獻1828條經驗 獲得超3個贊
擴展運算符創建淺表副本。如果菜單的內容是對象,則更改復制數組中的這些對象將更改原始數組中的這些對象(或者從技術上講,這兩個引用針對同一對象):
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)

繁花不似錦
TA貢獻1851條經驗 獲得超4個贊
我通過以下方式進行了深度克隆
const cloned = menu.getMenu().map(x => Object.assign({}, x));
? ? console.log('cloned ', cloned)
? ? this.menuItems = this.permissionService.filterMenuByTopic(cloned);
添加回答
舉報
0/150
提交
取消