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

一旦用户登录,我就通过权限过滤菜单数组。

我生成静态菜单,然后将数组的副本提供给过滤器。


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;

  }


}


绝地无双
浏览 42回答 2
2回答

倚天杖

扩展运算符创建浅表副本。如果菜单的内容是对象,则更改复制数组中的这些对象将更改原始数组中的这些对象(或者从技术上讲,这两个引用针对同一对象):const obj1 = {&nbsp; val: 1}const obj2 = {&nbsp; val: 2}const obj3 = {&nbsp; val: 3}const arr = [obj1, obj2, obj3]// creating a copy with the spread operatorconst copy = [...arr]// changing the second element in the copycopy[1].val = 22// the element in the original array is changed tooconsole.log(arr)

繁花不似锦

我通过以下方式进行了深度克隆const cloned = menu.getMenu().map(x => Object.assign({}, x));    console.log('cloned ', cloned)    this.menuItems = this.permissionService.filterMenuByTopic(cloned);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript