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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21562659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:11:45  来源:igfitidea点击:

Can I write an if statement within a Javascript object when setting an attribute?

javascript

提问by Jorge Olivero

Setting attributeTwo using an if statement. What is the correct way to do this?

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

var testBoolean = true;

var object = {
  attributeOne: "attributeOne",
  attributeTwo: if (testBoolean) { "attributeTwo" } else { "attributeTwoToo" },
}

回答by Matt

No, however you can use the ternary operator:

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

var testBoolean = true;

var object = {
  attributeOne: "attributeOne",
  attributeTwo: testBoolean ? "attributeTwo" : "attributeTwoToo"
}

回答by Tony Nardi

You can use an if statement, if it is within a immediately invoked function.

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

var x = {
  y: (function(){
       if (true) return 'somevalue';
     }())
};

回答by bajran

you can also do by this method

你也可以用这个方法

var testBoolean = true;

var object = {
  attributeOne: "attributeOne"
}

1

1

if(testBoolean){
   object.attributeTwo = "attributeTwo"
}else{
   object.attributeTwo = "attributeTwoToo"
}

2

2

object.attributeTwo = testBoolean ? "attributeTwo" : "attributeTwoToo"

回答by Andrew Clark

You can't use an if statement directly, but you can use ternary operator(aka conditional operator) which behaves the way you want. Here is how it would look:

您不能直接使用 if 语句,但您可以使用按您想要的方式运行的三元运算符(又名条件运算符)。这是它的外观:

var testBoolean = true;

var object = {
  attributeOne: "attributeOne",
  attributeTwo: testBoolean ? "attributeTwo" : "attributeTwoToo"
}

回答by HieuHT

Indeed you can but why don't you do the conditional statement before assigning it to object attribute. The code would be nicer.

确实可以,但为什么不在将其分配给对象属性之前执行条件语句。代码会更好。