Я получаю некоторые неожиданные поведения (согласно моей концепции) при выполнении некоторых 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
без изменения значения исходного массива?