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