TypeError:无法读取JavaScript中未定义的属性“ push”

我有一个称为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);

但是我得到以下错误: TypeError:无法读取未定义的属性“ push” 。 在此先感谢您的帮助。 干杯

weilinloveliulina 回答:TypeError:无法读取JavaScript中未定义的属性“ push”

请尝试这个。

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
  });
}

,

在倒数第二行中,您将一个字符串分配给输入,然后再将其用作数组。在您尝试推送时,输入不再是数组类型。

请记住,注释也是数组,因此您可以取出.comment并输入注释数组。

,

您可以采取一些措施来改进代码:

  • 尝试检查req.params.id是否存在
  • test[req.params.id].comments.comment不是数组,但是string
  • 将变量名从input更改为commentscomment**s**意味着很多,因此对于其他将要读取代码的人来说,它可以是数组)

所以代码应该像这样

if (req && req.params &&  req.params.id) {
   // the other code is omitted for the brevity
   let comments = test[req.params.id].comments;
   comments.push(req.body.comment);
}
本文链接:https://www.f2er.com/3040689.html

大家都在问