添加新对象时循环和条件?

时间:2012-06-19 20:35:02

标签: javascript

我尝试这样做:

posts[fbposts[fbpost].id] = ({
    name: fbposts[fbpost].from.name,
    link: "http://www.facebook.com/" + fbposts[fbpost].from.id,
    img: "http://graph.facebook.com/" + fbposts[fbpost].from.id + "/picture",
    message: fbposts[fbpost].message,
    to: ({
        name: name,
        link: link,
    }),
    created: timeDifference(Date.parse((fbposts[fbpost].updated_time))),
    sortvar: (Date.parse(fbposts[fbpost].updated_time)),
    comments: ({
        /* looping through the comments*/
        if (fbposts[fbpost].comments.count) {
            for (var comment in fbposts[fbpost].comments.data) {
                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));
            }
        }
    })
});
}

但很明显,当我得到评论时,脚本会刹车,因为我无法在对象声明中运行循环和条件。我应该怎么做呢?

2 个答案:

答案 0 :(得分:1)

您应该创建一个传递必要参数的函数,并将其用于comments属性,例如:

comments: (/* return value from your function */)

答案 1 :(得分:1)

实际上,你可以使用闭包来做到这一点......

comments: function() { ... looping code ...; return data}(),

这样做是定义一个内联(单用)函数并立即调用它,返回有效的javascript。

var x = {
    ten: 10, 
    thirty: function(){var a = 10; a += 20; return a}(), 
    fifty: 25+25};

x现在是一个看起来像这样的对象:

ten: 10
thirty: 30
fifty: 50