如何检查JavaScript中的对象属性是否未定义?
当前回答
与void 0进行比较,以获得简洁性。
if (foo !== void 0)
它不像(typeoffoo!=='undefined')那样冗长
其他回答
function isUnset(inp) {
return (typeof inp === 'undefined')
}
如果变量已设置,则返回false;如果未定义,则返回true。
然后使用:
if (isUnset(var)) {
// initialize variable here
}
if (somevariable == undefined) {
alert('the variable is not defined!');
}
您也可以将其转换为函数,如下所示:
function isset(varname){
return(typeof(window[varname]) != 'undefined');
}
读到这里,我很惊讶我没有看到这一点。我已经找到了多种算法可以解决这个问题。
从未定义
如果从未定义对象的值,那么如果将其定义为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");
}
“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。
"propertyName" in obj //-> true | false