javascript - 尝试插入数组会在 angular6 中出现错误

标签 javascript angular push

我想对数组进行排序并将获取的值存储到新数组中以供打印。我尝试使用 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)
    })

`

最佳答案

不要使用难以阅读和维护的for循环,你最好使用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)
});

关于javascript - 尝试插入数组会在 angular6 中出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54121215/

相关文章:

javascript - 如何从一个流获取在其他流的最后一个事件之后发生的事件

angular - OAuth2 使用 Angular angular-oauth2-oidc 和 SSO

git - 想要 git post receive hook 来进行新的提交和推送

javascript - 在 AngularJS 中获取选定的选项

javascript - HTML表格-为每个<td>创建弹出框并显示xml数据

javascript - graphqlj-js 联合类型,访问参数

angular2-jwt token.split 不是函数

git - 基于 groovy 的 Jenkins 流水线 : unable to push into git => Permission denied (publickey)

ruby - 如何在 Ruby 中创建哈希数组

javascript - <button type ="submit"> onclick 提交两次?