在javascript中向变量添加其他对象?

时间:2012-06-19 21:17:53

标签: javascript

我有一个可能包含对象的变量,或者可能是未定义的。我希望为此变量添加其他对象。我该怎么做?

适用时的代码示例:

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

2 个答案:

答案 0 :(得分:2)

测试它是否未定义,如果是,则将其分配给空对象:

if (typeof yourVar === "undefined")
    yourVar = {};

yourVar.additionalObject1 = { something : "test" };
yourVar.additionalObject2 = { something : "else" };

编辑:好的,既然您已经在问题中添加了代码,那么您的comments变量似乎应该是一个数组,因为您是在循环中添加它。所以我想你想做这样的事情:

(function(){ 
    var comments = [];
    if(fbposts[fbpost].comments.count){
        for(var comment in fbposts[fbpost].comments.data){
                comments.push({
                    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;
})();
因此,

comments将为源数据中的每个注释包含一个元素。如果没有注释,它将是一个空数组。 (如果您希望它返回undefined如果没有注释,则将变量声明保留为var comments,并在comments=[];语句中添加if。)< / p>

答案 1 :(得分:0)

如果您正在使用jQuery(为什么不成为?),那么您想要查看$.extend()

http://api.jquery.com/jQuery.extend/