I have a variable that may contain objects or may be undefined. I wish to add additional objects to this variable. How do I do that?
code example when applicable:
function(){
var comments;
if(fbposts[fbpost].comments.count){
for(var comment in fbposts[fbpost].comments.data){
comments = ({
name: fbposts[fbpost].comments.data[comment].from.name,
link: "http://www.facebook.com/"+fbposts[fbpost].comments.data[comment].from.id,
img: "http://www.facebook.com/"+fbposts[fbpost].comments.data[comment].from.id+"/picture",
message: fbposts[fbpost].comments.data[comment].message,
created: timeDifference(Date.parse(fbposts[fbpost].comments.data[comment].created_time)),
})
}
}
return comments;}(),
Test if it is undefined and if so assign it to an empty object:
EDIT: OK, now that you’ve added code to your question, it seems like your
commentsvariable should be an array, since you are adding to it in a loop. So I think you’d want to do something like this:commentswill thus contain one element for each comment in your source data. If there are no comments it will be an empty array. (If you want it to returnundefinedif there are no comments then leave the variable declaration where it is asvar commentsand addcomments=[];just inside theifstatement.)