代码之家  ›  专栏  ›  技术社区  ›  Junaid

角度:如何将一个数组复制到另一个数组?

  •  0
  • Junaid  · 技术社区  · 6 年前

    我正在设置一个数组与另一个数组相等

            orders = [
               {
                'id': PROCESSING,
                'displayName': 'Processing'
               },
               {
                'id': SHIPPED,
                'displayName': 'Shipped'
               }
            ];
    
            cloneOrders = [];
    
    setOrders() {
            this.orders.forEach((order: any) => {
                    this.cloneOrders = order;
            });
        }
    

    但当我尝试在另一个函数中获取'cloneOrders'的值时,它返回一个空数组

    getOrders(status, minutes) {
            this.cloneOrders .forEach((order: any) => {
                    console.log(order);
            });
        }
    

    这两个功能位于同一个组件中。请帮我解决这个问题谢谢。

    5 回复  |  直到 6 年前
        1
  •  9
  •   Rahul    6 年前

    像这样试试

    setOrders() {
            this.cloneOrders= [...this.orders];
        }
    

        2
  •  1
  •   Sajeetharan    6 年前

    您需要.push以向数组中添加项,

    this.orders.forEach((order: any) => {
           this.cloneOrders.push(order);
     });
    

    setOrders() {
            this.cloneOrders= [...this.orders];
    }
    
        3
  •  1
  •   Sunil Singh    6 年前

    如果你想做深度克隆-

    let cloned = this.cloneOrders.map(x => Object.assign({}, x));
    
        4
  •  0
  •   Artyom Amiryan    6 年前

    orders cloneOrders ,你需要推动它 命令 克隆目

    setOrders() {
            this.orders.forEach((order: any) => {
                    this.cloneOrders.push(order);
            });
        }
    
        5
  •  0
  •   ishani shah    6 年前

    我们可以使用扩展运算符使用ES6

    orders = [
     {'id': PROCESSING,'displayName': 'Processing'},
     {'id': SHIPPED,'displayName': 'Shipped'}
    ];
    
    cloneOrders = [];
    
    setOrders(){
      this.cloneOrders= [...this.orders];
    }