设置属性时,我可以在Javascript对象中编写if语句吗?

Jor*_*ero 11 javascript

使用if语句设置attributeTwo.这样做的正确方法是什么?

var testBoolean = true;

var object = {
  attributeOne: "attributeOne",
  attributeTwo: if (testBoolean) { "attributeTwo" } else { "attributeTwoToo" },
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 34

不,但是你可以使用三元运算符:

var testBoolean = true;

var object = {
  attributeOne: "attributeOne",
  attributeTwo: testBoolean ? "attributeTwo" : "attributeTwoToo"
}
Run Code Online (Sandbox Code Playgroud)


And*_*ark 5

您不能直接使用 if 语句,但可以使用三元运算符(也称为条件运算符),其行为符合您想要的方式。其外观如下:

var testBoolean = true;

var object = {
  attributeOne: "attributeOne",
  attributeTwo: testBoolean ? "attributeTwo" : "attributeTwoToo"
}
Run Code Online (Sandbox Code Playgroud)


小智 5

如果在立即调用的函数中,则可以使用if语句。

var x = {
  y: (function(){
       if (true) return 'somevalue';
     }())
};
Run Code Online (Sandbox Code Playgroud)