为了账号安全,请及时绑定邮箱和手机立即绑定

为什么对数组副本进行更改会影响原始数组?

为什么对数组副本进行更改会影响原始数组?

绝地无双 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 关注
  • 37 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信