2012-01-17 48 views
1

我想追加只有當條件滿足(距離!=「關」)的值。在某些情況下將值追加到對象?

這是我試過,但我不能得到它的工作?

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

怎麼辦?

回答

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將意味着地理編碼被定義和你需要檢查空或無論你決定的默認值應爲。選項2意味着地理編碼是未定義的,這是您建議您想要對原始代碼示例進行的操作。

+0

+1,該死的......在我前面的只有幾秒鐘:) – Alex 2012-01-17 22:54:02

+0

有其他方式,如IEFE:'VAR PARAMS =(函數(){VAR OBJ = {...};如果(。 ..)obj.goecode = ...; return obj;}());' – RobG 2012-01-18 02:13:22

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

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

這是* *究竟什麼Liso22一直在尋找;沒有辦法讓'geocode'在更短的時間內未定義。爲什麼downvote? – copy 2012-01-17 22:58:33

相關問題