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


当前回答

我不确定将==与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

其他回答

检查是否存在密钥的一种简单方法是:

if (key in obj) {
  // Do something
} else {
  // Create key
}

const obj = {
  0: 'abc',
  1: 'def'
}

const hasZero = 0 in obj

console.log(hasZero) // true

以下是我的情况:

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

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

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

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

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

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

查看注释,对于那些想同时检查两者的人来说,它是未定义的还是其值为空:

//Just in JavaScript
var s; // Undefined
if (typeof s == "undefined" || s === null){
    alert('either it is undefined or value is null')
}

如果您使用的是jQueryLibrary,那么jQuery.isEmptyObject()将足以满足这两种情况,

var s; // Undefined
jQuery.isEmptyObject(s); // Will return true;

s = null; // Defined as null
jQuery.isEmptyObject(s); // Will return true;

//Usage
if (jQuery.isEmptyObject(s)) {
    alert('Either variable:s is undefined or its value is null');
} else {
     alert('variable:s has value ' + s);
}

s = 'something'; // Defined with some value
jQuery.isEmptyObject(s); // Will return false;

我很惊讶我还没有看到这个建议,但它比使用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
}

读到这里,我很惊讶我没有看到这一点。我已经找到了多种算法可以解决这个问题。

从未定义

如果从未定义对象的值,那么如果将其定义为null或undefined,则将无法返回true。如果您希望为设置为undefined的值返回true,这很有用

if(obj.prop === void 0) console.log("The value has never been defined");

定义为未定义或从未定义

如果您希望使用undefined值定义的值或从未定义的值的结果为true,则可以简单地使用==undefineed

if(obj.prop === undefined) console.log("The value is defined as undefined, or never defined");

定义为错误值、未定义、空或从未定义。

通常,人们要求我提供一种算法,以确定某个值是否为假值、未定义值或空值。以下工作。

if(obj.prop == false || obj.prop === null || obj.prop === undefined) {
    console.log("The value is falsy, null, or undefined");
}