Detecting an undefined object property

后端 未结 30 2982
花落未央
花落未央 2020-11-21 04:43

What\'s the best way of checking if an object property in JavaScript is undefined?

30条回答
  •  青春惊慌失措
    2020-11-21 05:34

    There is a nice and elegant way to assign a defined property to a new variable if it is defined or assign a default value to it as a fallback if it’s undefined.

    var a = obj.prop || defaultValue;
    

    It’s suitable if you have a function, which receives an additional configuration property:

    var yourFunction = function(config){
    
       this.config = config || {};
       this.yourConfigValue = config.yourConfigValue || 1;
       console.log(this.yourConfigValue);
    }
    

    Now executing

    yourFunction({yourConfigValue:2});
    //=> 2
    
    yourFunction();
    //=> 1
    
    yourFunction({otherProperty:5});
    //=> 1
    

提交回复
热议问题