javascript - Array.prototype 函数(.map()、.reduce() 等)更改 Angular 2+ 中模型变量的值

标签 javascript angular typescript dictionary angular7

在执行一些 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/

相关文章:

javascript - 如何通过缓动增加 javascript 循环延迟

javascript - Angular 2 : Expression has changed after it was checked on accessing child component property

Angular 2 为单个服务或每个请求禁用 XSRFStrategy

typescript - React-Redux useSelector typescript 类型的状态

javascript - 使用 Rx 扫描运算符将流减少为值

javascript - 在谷歌地图中仅显示特定国家(地区)

javascript - 如何将数组插入对象中

javascript - fullPage.js 滚动幻灯片到不同方向

node.js - grunt 构建中的问题

typescript - NestJS 记录唯一请求跟踪