【问题标题】:Attempting to push into array gives error in angular6尝试推入数组会导致 angular6 出现错误
【发布时间】:2019-01-10 02:34:42
【问题描述】:

我想对数组进行排序并将获取的值存储到一个新数组中以供打印。我尝试使用 push(),但出现错误并显示“无法读取未定义的属性 'push'”。

`

this.dataService.userprofile().subscribe((data:any) => {
      let profile:any[]=data.profiles;
      for(let index=0;index<profile.length;index++) {
        const element = profile[index];  
        const today: number = Date.now();
        var b = Math.abs(today - Date.parse(element["dob"]));
        element["dob"] = Math.floor(b / (1000 * 3600 * 24 * 365.25));
        if (element["active"]=="N"){
          this.row.push(element); 
        }}
      this.rowData = this.row;//ag-grid row
      console.log(this.rowData)
    })

`

【问题讨论】:

  • this.row 是否在您的函数上下文中以任何方式初始化?
  • this.row = (this.row || []).concat(element);
  • @Paqman 我认为row 是一个局部变量,用于存储elements 的数组并填充初始化的this.rowData.. 在我的回答中,我建议直接使用this.rowData 分配Array.prototype.reduce() 的结果

标签: javascript angular push


【解决方案1】:

不要使用难以阅读和维护的for loop,最好使用Array.prototype.reduce() 并使用点符号

还要注意在 TypeScript 中你应该避免使用类型any

代码:

this.dataService.userprofile().subscribe((data: any) => {
  this.rowData = data.profiles.reduce((acc, element) => {
    const b = Math.abs(today - Date.parse(element.dob));
    element.dob = Math.floor(b / (1000 * 3600 * 24 * 365.25));
    return element.active == 'N' ? [...acc, element] : acc;
  }, []);

  console.log(this.rowData)
});

【讨论】:

    【解决方案2】:

    在for循环之前声明row变量。

    this.dataService.userprofile().subscribe((data:any) => {
          let profile:any[]=data.profiles;
          let row = [];
          for(let index=0;index<profile.length;index++) {
            const element = profile[index];  
            const today: number = Date.now();
            var b = Math.abs(today - Date.parse(element["dob"]));
            element["dob"] = Math.floor(b / (1000 * 3600 * 24 * 365.25));
            if (element["active"]=="N"){
              row.push(element); 
            }}
          this.rowData = row;//ag-grid row
          console.log(this.rowData)
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-07
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 2020-12-17
      • 1970-01-01
      相关资源
      最近更新 更多