亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么對數組副本進行更改會影響原始數組?

為什么對數組副本進行更改會影響原始數組?

絕地無雙 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)


查看完整回答
反對 回復 2024-01-18
?
繁花不似錦

TA貢獻1851條經驗 獲得超4個贊

我通過以下方式進行了深度克隆


const cloned = menu.getMenu().map(x => Object.assign({}, x));

? ? console.log('cloned ', cloned)

? ? this.menuItems = this.permissionService.filterMenuByTopic(cloned);

查看完整回答
反對 回復 2024-01-18
  • 2 回答
  • 0 關注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號