首页 > 解决方案 > 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函数而不改变其原始数组的值?

标签: javascriptangulartypescriptdictionaryangular7

解决方案


你应该这样做:

array.map(el => ({key: el.key, value: 1000}))

尽管map确实创建了一个新数组,但它不会创建其元素的新实例。所以如果你修改一个元素,它也会在原始数组中被修改。这就是为什么您需要创建一个新对象。


要创建较大对象的浅表副本,您可以执行以下操作:

Object.assign({}, el, { value: 1000 })

这会将 的所有属性分配el给新对象,然后分配value给新对象。如果value已经存在,它将被覆盖。


推荐阅读