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


当前回答

以下是我的情况:

我正在使用REST调用的结果。结果应该从JSON解析为JavaScript对象。

有一个错误我需要辩护。如果REST调用的参数不正确,并且用户指定了错误的参数,则REST调用基本上返回为空。

在使用这篇文章来帮助我抵御这一挑战时,我尝试了这样做:

if( typeof restResult.data[0] === "undefined" ) { throw  "Some error"; }

对于我的情况,如果restResult.data[0]==“object”,那么我可以安全地开始检查其余成员。如果未定义,则抛出上述错误。

我想说的是,就我的情况而言,本文中之前的所有建议都不起作用。我并不是说我是对的,每个人都是错的。我根本不是一个JavaScript大师,但希望这会对某人有所帮助。

其他回答

检查属性值是否为未定义的特殊值的通常方法是:

if(o.myProperty === undefined) {
  alert("myProperty value is the special value `undefined`");
}

要检查对象是否实际上没有这样的属性,并且当您尝试访问它时,默认情况下会返回undefined:

if(!o.hasOwnProperty('myProperty')) {
  alert("myProperty does not exist");
}

要检查与标识符关联的值是否为未定义的特殊值,或者该标识符是否尚未声明:

if(typeof myVariable === 'undefined') {
  alert('myVariable is either the special value `undefined`, or it has not been declared');
}

注意:最后一个方法是引用未声明的标识符而不出现早期错误的唯一方法,这与值为undefined不同。

在ECMAScript 5之前的JavaScript版本中,全局对象上名为“undefined”的属性是可写的,因此,如果不小心重新定义了foo==undefineed,则简单的检查可能会出现意外的行为。在现代JavaScript中,属性是只读的。

然而,在现代JavaScript中,“undefined”不是关键字,因此函数内部的变量可以命名为“undefine”,并隐藏全局属性。

如果您担心这种(不太可能的)边缘情况,可以使用void运算符获取特殊的未定义值本身:

if(myVariable === void 0) {
  alert("myVariable is the special value `undefined`");
}

我很惊讶我还没有看到这个建议,但它比使用typeof测试更具特异性。如果您需要知道对象属性是用undefined初始化的还是从未初始化过,请使用Object.getOwnPropertyDescriptor():

// to test someObject.someProperty
var descriptor = Object.getOwnPropertyDescriptor(someObject, 'someProperty');

if (typeof descriptor === 'undefined') {
  // was never initialized
} else if (typeof descriptor.value === 'undefined') {
  if (descriptor.get || descriptor.set) {
    // is an accessor property, defined via getter and setter
  } else {
    // is initialized with `undefined`
  }
} else {
  // is initialized with some other value
}

Use:

要检查属性是否未定义,请执行以下操作:

if (typeof something === "undefined") {
    alert("undefined");
}

要检查属性是否未定义,请执行以下操作:

if (typeof something !== "undefined") {
    alert("not undefined");
}

我不确定将==与typeof一起使用的起源,按照惯例,我在许多库中都使用了它,但typeof运算符返回字符串文本,我们事先就知道了,所以为什么还要对其进行类型检查呢?

typeof x;                      // some string literal "string", "object", "undefined"
if (typeof x === "string") {   // === is redundant because we already know typeof returns a string literal
if (typeof x == "string") {    // sufficient

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

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