我有一个名为 test 的数组,用于存储有关某个测试的信息。我正在开发评论功能,以便用户可以评论测试。目前用户只能发表一条评论,因为第二条评论会覆盖第一条评论。我现在想在每次输入评论时在数组“评论”中添加一个对象。
var test = [{
id: 0,
test_id: "Password test",
pass: 1,
fail: 5,
time: 0.03,
pass_fail: 20,
comments : [
{comment : "", commentuser : "" },
]
}
我使用 push() 函数来做到这一点:
app.post('/test/:id/comment', urlencodedParser, function(req, res) {
console.log("User Name : " + req.body.name);
console.log("User Comment: " + req.body.comment);
if (req.body.name && req.body.comment) {
console.log('Your comment was posted !');
res.sendFile(__dirname + '/HTML/comment-success.html');
//test[req.params.id].comment = req.body.comment ;
//test[req.params.id].commentuser = req.body.name ;
var input = test[req.params.id].comments.comment;
input.push(req.body.comment);
但是我收到以下错误: 类型错误:无法读取未定义的属性“推送”。 在此先感谢您的帮助。 干杯
最佳答案
请试试这个。
if (req.body.name && req.body.comment) {
console.log('Your comment was posted !');
res.sendFile(__dirname + '/HTML/comment-success.html');
//test[req.params.id].comment = req.body.comment ;
//test[req.params.id].commentuser = req.body.name ;
test[req.params.id].comments.push({
comment: req.body.comment,
commentuser: req.body.name
});
}
关于javascript - 类型错误:无法读取 JavaScript 中未定义的属性 'push',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59020981/