如何检查JavaScript中的对象属性是否未定义?


当前回答

如果定义了一个新变量,可以用一种优雅的方式将已定义的属性分配给它;如果未定义,则可以将默认值分配给它作为回退。

var a = obj.prop || defaultValue;

如果您有一个函数,它会接收一个额外的配置属性,那么这是合适的:

var yourFunction = function(config){

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

正在执行

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

yourFunction();
//=> 1

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

其他回答

同样的事情也可以写得更短:

if (!variable){
    // Do it if the variable is undefined
}

or

if (variable){
    // Do it if the variable is defined
}
function isUnset(inp) {
  return (typeof inp === 'undefined')
}

如果变量已设置,则返回false;如果未定义,则返回true。

然后使用:

if (isUnset(var)) {
  // initialize variable here
}

您可以像这样使用JavaScript对象函数:

var ojb ={
    age: 12
}

if(ojb.hasOwnProperty('name')){
    console.log('property exists and is not undefined');
}

如果获得该属性或该属性未定义,则上述方法返回true。

我想向您展示我正在使用的一些东西,以保护未定义的变量:

Object.defineProperty(window, 'undefined', {});

这禁止任何人更改window.undefined值,从而破坏基于该变量的代码。如果使用“usestrict”,任何试图更改其值的行为都将以错误告终,否则将被忽略。

如果定义了一个新变量,可以用一种优雅的方式将已定义的属性分配给它;如果未定义,则可以将默认值分配给它作为回退。

var a = obj.prop || defaultValue;

如果您有一个函数,它会接收一个额外的配置属性,那么这是合适的:

var yourFunction = function(config){

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

正在执行

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

yourFunction();
//=> 1

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