如何检查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;
其他回答
“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。
解决方案不正确。在JavaScript中,
null == undefined
将返回true,因为它们都“强制”为布尔值,并且都为false。正确的方法是检查
if (something === undefined)
这是身份运算符。。。
我们ES6可以与!!将所有值转换为布尔值。使用此选项,所有假值都将变为假。
第一种解决方案
if (!(!!variable)) {
// Code
}
第二种解决方案
if (!variable) {
// Code
}
在JavaScript中,存在null和undefined。它们有不同的含义。
undefined表示变量值尚未定义;不知道值是多少。null表示变量值被定义并设置为null(没有值)。
Marijn Haverbeke在他的免费在线书《Eloquent JavaScript》(我的重点)中写道:
还有一个类似的值null,其含义是“此值已定义,但没有值”。undefined和null之间的含义差异主要是学术性的,通常不太有趣。在实际程序中,经常需要检查某个东西是否“有价值”。在这些情况下,可以使用表达式something==undefined,因为即使它们不是完全相同的值,null==undefine也会产生true。
所以,我想最好的检查方法是:
if (something == undefined)
对象财产的工作方式应该相同。
var person = {
name: "John",
age: 28,
sex: "male"
};
alert(person.name); // "John"
alert(person.fakeVariable); // undefined
如果使用的是Angular:
angular.isUndefined(obj)
angular.isUndefined(obj.prop)
Undercore.js:
_.isUndefined(obj)
_.isUndefined(obj.prop)