javascript - 为什么更改数组的副本会影响原始数组?
问题描述
用户登录后,我按权限过滤菜单数组。
我生成静态菜单,然后将数组副本提供给过滤器。
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;
}
}
解决方案
扩展运算符创建一个浅拷贝。如果菜单的内容是对象,那么更改副本数组中的这些对象将更改原始数组中的那些对象(或者从技术上讲,这两个引用是针对同一个对象的):
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)
推荐阅读
- r - 替代 R 中的子集?
- java - 在arraylist中创建新对象
- eclipse - 当前在 MacOS 上运行时无法打开 Eclipse 的第二个实例
- python - "django.db.utils.ProgrammingError: 关系 "silk_request" 不存在 LINE 1: INSERT INTO "silk_reque 是什么意思?
- hadoop - 是否有任何 Hive SQL 函数来评估字段是否包含字母?
- python - 如何使用 pytexit 显示乘法和除法符号?
- java - Java SpringBoot - 空列表的@Value
- javascript - 如何在反应中将第一个状态数据分配给第二个状态?
- python - 无法在 Django Celery Beat 的函数中获取 kwargs 数据
- python - 键盘记录器未记录 txt 文档中的字符