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

前端 未结 5 1056
自闭症患者
自闭症患者 2021-01-03 23:30

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

var testBoolean = true;

var object = {
  attributeOne: \"attributeOne\",
  a         


        
5条回答
  •  太阳男子
    2021-01-04 00:20

    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:

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

提交回复
热议问题