gpt4 book ai didi

javascript - angularjs:推送不是一个函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:31:27 24 4
gpt4 key购买 nike

我有一个像这样的 JSON 对象:

var post = {
"post_id": "1",
"content": "content",
"post_author": {
"id": "12",
"firstName": "Amelia",
"lastName": "Earheart",
},
"isLiked": false,
"likes_count": 0,
"likers": [],
"comments_count": 0,
"commenters": [],
"comments": []
};

并且post从前端传递给下面给出的函数。

var vm = this;
vm.likePost = function(post) {
var likedPost = post;
vm.userInfo();
likedPost.likers.push(userObject); //Here

myService.postLike(likedPost).success(function(data) {
likedPost.isLiked = true;
likedPost.likes_count++;
vm.posts = data;
});
};

但这样做时,我在 likedPost.likers.push(userObject);

行中收到一个 JavaScript 错误,提示 push is not a function

userObjectvm.userInfo() 返回,它看起来像这样:

vm.userInfo = function() {
myService.getBasicUserInfo().success(function(data) {
vm.currentPost.post_author.id = data.id;
vm.currentPost.post_author.firstName = data.firstName;
vm.currentPost.post_author.lastName = data.lastName;
});
};

返回的JSON是这样的:

{"id":"12","firstName":"Amelia","lastName":"Earheart"}

谁能帮我找出这个问题的原因?

更新:

{
"post_id": "12",
"content": "Content is the content that contains the content",
"image": "member-default.jpg",
"created_at": "2016-05-26 14:29:00",
"post_author": {
"id": "12",
"firstName": "Amelia",
"lastName": "Earheart",
},
"isLiked": false,
}

这是我在 console.log(likedPost);

上得到的

最佳答案

输出明确指出 likers 未定义。您可以在使用 push() 方法之前进行验证检查。

//if likedPost.likers is not defined, it will define it as an array 
likedPost.likers = likedPost.likers || [];

//Do the push operation
likedPost.likers.push(userObject);

关于javascript - angularjs:推送不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37807894/

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