Conditionally set an object property

后端 未结 6 1967
太阳男子
太阳男子 2020-12-04 17:37

Is there some syntax for setting properties based on a condition?

data: {
    userId: 7,
    actionId: 36,
    express: (myCondition ? true : null) // does n         


        
6条回答
  •  隐瞒了意图╮
    2020-12-04 18:06

    You can do it if you define your object using an anonymous function instead of object literal notation:

    var data = new function(){
        this.userId = 7;
        this.actionId = 36;
        myCondition && (this.express = true);
    };
    

    The resulting data object is the exact same, except it's constructor will be the anonymous function instead of window.Object.

提交回复
热议问题