如何检查JavaScript中的对象属性是否未定义?
当前回答
我假设您还想检查它是否未定义或为空。如果是,我建议:
myVar==空
这是唯一一次双等于非常有用,因为当myVar未定义或为null时,它将求值为true,但当它是其他假值(如0、false、“”和NaN)时,它会求值为false。
这是Lodash的isNil方法的实际源代码。
其他回答
我假设您还想检查它是否未定义或为空。如果是,我建议:
myVar==空
这是唯一一次双等于非常有用,因为当myVar未定义或为null时,它将求值为true,但当它是其他假值(如0、false、“”和NaN)时,它会求值为false。
这是Lodash的isNil方法的实际源代码。
"propertyName" in obj //-> true | false
我不确定将==与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
来自lodash.js。
var undefined;
function isUndefined(value) {
return value === undefined;
}
它创建了一个名为undefined的局部变量,该变量用默认值(即真正的undefineed)初始化,然后将该值与变量undefine进行比较。
更新日期:2019年9月9日
我发现Lodash更新了它的实现。查看我的问题和代码。
要做到防弹,只需使用:
function isUndefined(value) {
return value === void 0;
}
查看注释,对于那些想同时检查两者的人来说,它是未定义的还是其值为空:
//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;