javascript - Array.prototype 函数(.map()、.reduce() 等)在 Angular 2+ 中更改模型变量的值
问题描述
Array.prototype
在执行某些功能(例如.map
,.reduce
等)时,我得到了一些意想不到的行为(根据我的概念)。问题是这个函数正在改变模型变量的值。我创建了一段代码来重现它:
import { Component, OnInit } from '@angular/core';
const getServerData = [
{ key: 'test1', value: 1 },
{ key: 'test2', value: 2 },
{ key: 'test3', value: 3 },
{ key: 'test4', value: 4 },
];
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
// docs receive values of const getServerData
docs = getServerData;
ngOnInit() {
const test = this.mapFunctionTest(this.docs);
console.log(this.docs);
}
// Here is the problem. I don't know why mapFunctionTest modifies the values
// of docs (value = 1000). What I expect is that the constant test should
// receive the returned array from mapFunctionTest and the value of docs
// keep unalterated (and wasn't assigned to value = 1000)
mapFunctionTest(array: any[]): any[] {
const testedArray = array.map((element) => {
element.value = 1000;
return element;
});
return testedArray;
}
}
我对这段代码的意图是常量“test”接收从函数返回的数组,其中mapFunctionTest
包含以下值:
[
{key: "test1", value: 1000},
{key: "test2", value: 1000},
{key: "test3", value: 1000},
{key: "test4", value: 1000}
]
而 docs 变量保持其内容不变(这没有发生):
[
{key: "test1", value: 1},
{key: "test2", value: 2},
{key: "test3", value: 3},
{key: "test4", value: 4}
]
如何使用Array.prototype
函数而不改变其原始数组的值?
解决方案
你应该这样做:
array.map(el => ({key: el.key, value: 1000}))
尽管map
确实创建了一个新数组,但它不会创建其元素的新实例。所以如果你修改一个元素,它也会在原始数组中被修改。这就是为什么您需要创建一个新对象。
要创建较大对象的浅表副本,您可以执行以下操作:
Object.assign({}, el, { value: 1000 })
这会将 的所有属性分配el
给新对象,然后分配value
给新对象。如果value
已经存在,它将被覆盖。
推荐阅读
- windows - 通过批处理文件远程注册
- elasticsearch - elasticsearch中的同义词与复数短语不匹配
- extjs - bootstrap时如何判断环境是什么
- javascript - 数据中的Ajax传递参数发送到php
- javascript - Google 表格秒表
- angular - 在过滤器中搜索数据时,我想在 Angular SlickGrid 中使用空数据集搜索结果时显示“没有要显示的数据”
- vue.js - 如何在 Quasar Vue Google Maps 上修复无法读取 null 的属性“地图”?
- c# - C#如何通过字符串获取对象属性?
- javascript - JQuery动态验证多维数组中的文件大小
- c++ - 如何继承获取类对象c ++的类构造函数