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


当前回答

“if(window.x){}”是错误安全的

很可能您想要if(window.x)。即使x尚未声明(var x;),该检查也是安全的-浏览器不会抛出错误。

示例:我想知道我的浏览器是否支持历史API

if (window.history) {
    history.call_some_function();
}

工作原理:

window是一个包含所有全局变量作为其成员的对象,尝试访问不存在的成员是合法的。如果x尚未声明或未设置,则window.x返回undefined。undefined在if()求值时导致false。

其他回答

Use:

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

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

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

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

我找到了这篇文章,《在JavaScript中处理未定义的7个技巧》,它展示了关于未定义的真正有趣的事情如:

undefined的存在是JavaScript的许可性质的结果,允许使用:

未初始化变量不存在的对象财产或方法访问数组元素的越界索引不返回任何内容的函数的调用结果

if (somevariable == undefined) {
  alert('the variable is not defined!');
}

您也可以将其转换为函数,如下所示:

function isset(varname){
  return(typeof(window[varname]) != 'undefined');
}
"propertyName" in obj //-> true | false

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

//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;