首页 > 解决方案 > Angular 8:数组 .map() .slice() 无功能

问题描述

带有 Firebase 的 Angular 8:数组 .map () .slice () 不起作用。你好。我一直在尝试使用 Angular 8 中的 .map () 和 .slice () 来制作数组的副本,但是使用这些方法我发现复制的数组仍然具有对原始数组的引用。

我不知道我是否做错了,或者这些方法在 Angular 8 中不起作用。

 // Iniciamos la escucha de los cambios de la data del usuario
    if (!this.$userData) {
      this.$userData = this.userService.user().valueChanges().subscribe(data => {
        if (data) {
          this.userData = Object.assign({}, data);
          const temp = data.operationsList.map((x) => {
            x.bank = 'Popular';
            return x;
          });
          console.log(this.userData.operationsList, temp);
          if (!this.userData.validated) {
            this.router.navigate(['register/pendingValidation']);
          }
        }
      });
    }

控制台日志:

(2) [{…}, {…}]
0: {bank: "Popular", commission: 0, country: "ve", countryAllowed: "all", maximum: 0, …}
1: {bank: "Popular", commission: 0, country: "ve", countryAllowed: "all", maximum: 0, …}

(2) [{…}, {…}]
0: {bank: "Popular", commission: 0, country: "ve", countryAllowed: "all", maximum: 0, …}
1: {bank: "Popular", commission: 0, country: "ve", countryAllowed: "all", maximum: 0, …}

修改复制的数组时,更改也会反映在原始数组中。

标签: javascriptarraysangulartypescriptfirebase

解决方案


通过复制数组,您仍然保留对相同对象的引用。所以你需要更深一层:

const temp = data.operationsList.map((x) => Object.assign({}, x, { bank: 'Popular' }));

推荐阅读