2012-11-07 34 views
1

只是試圖做這樣的事情,它不會工作,想知道是否有嗎?條件變量在對象

var obj = { 
    intiger:5, 
    conditional:(something) ? "something" : "nothing", 
    string:"nothing important" 
}; 

這是因爲:conditional中存在的斷裂。無論如何要做到這一點,而不打破並保持這種格式obj

我知道我可以做。

obj.conditional = (something) ? "something" : "nothing"; 
+0

我的代碼與上面的例子不同,並且缺少圓括號。 – ThomasReggi

回答

4

使用另一組圓括號?

... 
conditional:((something)?"something":"nothing"), 
... 

只需要讓解析器知道哪個:要注意併爲此目的。

var foo = { 
    bar: (true ? "true" : "false") 
}; 
console.log(foo.bar); // true 

如果需要在參考時做出決定,您也可以使用function(){}。例如

var foo = { 
    bar:function(){ 
     return this.baz == 'Brad' ? 'Me' : 'Not Me'; 
    }, 
    baz: 'Brad' 
}; 
console.log(foo.bar()); // 'Me' 
foo.baz = 'Thomas'; console.log(foo.bar()); // 'Not Me'