Javascript 尝试推入数组会导致angular6出错
我想对数组进行排序,并将获取的值存储到新数组中进行打印。我尝试了push(),但出现了一个错误,显示“无法读取未定义的属性‘push’” `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) =>
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中,您应该避免使用typeany
代码:
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)
});