我的 oninit 中有以下数组设置:
this.tests = [{
status: 0,
testresults: [{
name: 'test',
id: 1
}]
}
]
;
this.tests.push([{
status: 1,
testresults: [{
name: 'test2',
id: 2
}]
}
]
}]);
这个数组按预期工作。我的目标是将查询结果推送到测试内部的 testresults 数组中。
this.tests[0].testresults.push(this.qryresults);
this.tests[1].testresults.push(this.qryresults);
索引 0 正常工作,索引 1 返回以下错误:
"ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined
TypeError: Cannot read property 'push' of undefined"
最佳答案
您第二次推送一个数组而不是一个额外的对象,这会导致错误,因为您推送的数组没有属性 testresults
。请参阅下面的代码片段以了解代码的工作修订:
(function() {
this.qryresults = "some test data"
this.tests = [{
status: 0,
testresults: [{
name: 'test',
id: 1
}]
}];
this.tests.push({ // <--- removed [ here
status: 1,
testresults: [{
name: 'test2',
id: 2
}]
}); // <--- removed ] here
this.tests[0].testresults.push(this.qryresults);
this.tests[1].testresults.push(this.qryresults);
console.log(this.tests)
})()
关于javascript - 为什么 Angular 会将索引 0 数组插入子数组而不是索引 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66392717/