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

前端 未结 5 1018
自闭症患者
自闭症患者 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:07

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

    0 讨论(0)
  • 2021-01-04 00:11

    No, however you can use the ternary operator:

    var testBoolean = true;
    
    var object = {
      attributeOne: "attributeOne",
      attributeTwo: testBoolean ? "attributeTwo" : "attributeTwoToo"
    }
    
    0 讨论(0)
  • 2021-01-04 00:11

    you can also do by this method

    var testBoolean = true;
    
    var object = {
      attributeOne: "attributeOne"
    }
    

    1

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

    2

    object.attributeTwo = testBoolean ? "attributeTwo" : "attributeTwoToo"
    
    0 讨论(0)
  • 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"
    }
    
    0 讨论(0)
  • 2021-01-04 00:21

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

    var x = {
      y: (function(){
           if (true) return 'somevalue';
         }())
    };
    
    0 讨论(0)
提交回复
热议问题