在执行一些 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
确实创建了一个新数组,但它不会创建其元素的新实例。所以如果你修改一个元素,它也会在原始数组中被修改。这就是您需要创建新对象的原因。
创建 shallow复制一个更大的对象,你可以这样做:
Object.assign({}, el, { value: 1000 })
这会将 el
的所有属性分配给一个新对象,然后将 value
分配给新对象。如果 value
已经存在,它将被覆盖。
关于javascript - Array.prototype 函数(.map()、.reduce() 等)更改 Angular 2+ 中模型变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54451467/