如何检查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。
其他回答
if ( typeof( something ) == "undefined")
这对我有用,而其他人没有。
我们ES6可以与!!将所有值转换为布尔值。使用此选项,所有假值都将变为假。
第一种解决方案
if (!(!!variable)) {
// Code
}
第二种解决方案
if (!variable) {
// Code
}
Use:
要检查属性是否未定义,请执行以下操作:
if (typeof something === "undefined") {
alert("undefined");
}
要检查属性是否未定义,请执行以下操作:
if (typeof something !== "undefined") {
alert("not undefined");
}
有一种非常简单的方法。
您可以使用可选链接:
x = {prop:{name:"sajad"}}
console.log(x.prop?.name) // Output is: "sajad"
console.log(x.prop?.lastName) // Output is: undefined
or
if(x.prop?.lastName) // The result of this 'if' statement is false and is not throwing an error
您甚至可以对函数或数组使用可选的链接。
截至2020年年中,这一点尚未得到普遍实施。查看文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
我认为这个问题有很多不正确的答案。与通常的看法相反,“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的情况下引发错误。