在某些条件下将值附加到对象?

时间:2012-01-17 22:47:50

标签: javascript

我只是在条件满足时才尝试附加值(距离!=“关闭”)。

这是我尝试的但我不能让它起作用?

var params = {
    q: pizza,
    result_type: "mixed",
    include_entities: "true",
    if(distance != "off") {
        geocode: geolocation,
        }
    rpp: 15,
    page: 1
};

怎么做?

2 个答案:

答案 0 :(得分:3)

Tou有两个不同含义的选项。

选项1:

var params = {
    q: pizza,
    result_type: "mixed",
    include_entities: "true",
    geocode: (distance != "off") ? geolocation:null,
    rpp: 15,
    page: 1
};

或选项2:

var params = {
    q: pizza,
    result_type: "mixed",
    include_entities: "true",
    rpp: 15,
    page: 1
};

if(distance != "off") {
    params.geocode: geolocation;
}

选项1意味着定义了地理编码,您需要检查null或您认为默认值应该是什么。选项2意味着地理编码未定义,这是您建议您对原始代码示例所做的。

答案 1 :(得分:1)

var params = {
    q: pizza,
    result_type: "mixed",
    include_entities: "true",
    rpp: 15,
    page: 1
};

if(distance != "off") {
    params.geocode = geolocation;
}