gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:46:49 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com