Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 尝试推入数组会导致angular6出错_Javascript_Angular_Push - Fatal编程技术网

Javascript 尝试推入数组会导致angular6出错

Javascript 尝试推入数组会导致angular6出错,javascript,angular,push,Javascript,Angular,Push,我想对数组进行排序,并将获取的值存储到新数组中进行打印。我尝试了push(),但出现了一个错误,显示“无法读取未定义的属性‘push’” ` this.dataService.userprofile().subscribe((数据:any)=>{ let profile:any[]=data.profiles; for(让index=0;index在for循环之前声明row变量) this.dataService.userprofile().subscribe((data:any) =>

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

`

this.dataService.userprofile().subscribe((数据:any)=>{
let profile:any[]=data.profiles;

for(让index=0;index在
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)
    })
this.dataService.userprofile().subscribe((数据:any)=>{
let profile:any[]=data.profiles;
设row=[];

对于(让index=0;index而不是使用
for loop
这是很难读取和维护的),最好使用和使用点符号

还要注意,在TypeScript中,您应该避免使用type
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)
});

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