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


当前回答

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

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

or

if (variable){
    // Do it if the variable is defined
}

其他回答

我认为这个问题有很多不正确的答案。与通常的看法相反,“undefined”在JavaScript中不是关键字,实际上可以为其赋值。

正确的代码

执行此测试的最可靠方法是:

if (typeof myVar === "undefined")

这将始终返回正确的结果,甚至可以处理未声明myVar的情况。

退化代码。不要使用。

var undefined = false;  // Shockingly, this is completely legal!
if (myVar === undefined) {
    alert("You have been misled. Run away!");
}

此外,myVar==undefined将在未声明myVar的情况下引发错误。

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

与void 0进行比较,以获得简洁性。

if (foo !== void 0)

它不像(typeoffoo!=='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
}

句柄未定义

function isUndefined(variable,defaultvalue=''){

    if (variable == undefined ) return defaultvalue;
    
    return variable;

}

变量obj={und:未定义,notundefined:“我没有定义”}函数isUndefined(变量,默认值=“”){if(变量==未定义){ 返回默认值;}返回变量}console.log(is未定义(obj.und,'i am print'))console.log(isUndefined(obj.notundefined,'Iam print'))