如何检查JavaScript中的对象属性是否未定义?
当前回答
如果定义了一个新变量,可以用一种优雅的方式将已定义的属性分配给它;如果未定义,则可以将默认值分配给它作为回退。
var a = obj.prop || defaultValue;
如果您有一个函数,它会接收一个额外的配置属性,那么这是合适的:
var yourFunction = function(config){
this.config = config || {};
this.yourConfigValue = config.yourConfigValue || 1;
console.log(this.yourConfigValue);
}
正在执行
yourFunction({yourConfigValue:2});
//=> 2
yourFunction();
//=> 1
yourFunction({otherProperty:5});
//=> 1
其他回答
同样的事情也可以写得更短:
if (!variable){
// Do it if the variable is undefined
}
or
if (variable){
// Do it if the variable is defined
}
检查属性值是否为未定义的特殊值的通常方法是:
if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
要检查对象是否实际上没有这样的属性,并且当您尝试访问它时,默认情况下会返回undefined:
if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
要检查与标识符关联的值是否为未定义的特殊值,或者该标识符是否尚未声明:
if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
注意:最后一个方法是引用未声明的标识符而不出现早期错误的唯一方法,这与值为undefined不同。
在ECMAScript 5之前的JavaScript版本中,全局对象上名为“undefined”的属性是可写的,因此,如果不小心重新定义了foo==undefineed,则简单的检查可能会出现意外的行为。在现代JavaScript中,属性是只读的。
然而,在现代JavaScript中,“undefined”不是关键字,因此函数内部的变量可以命名为“undefine”,并隐藏全局属性。
如果您担心这种(不太可能的)边缘情况,可以使用void运算符获取特殊的未定义值本身:
if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
解决方案不正确。在JavaScript中,
null == undefined
将返回true,因为它们都“强制”为布尔值,并且都为false。正确的方法是检查
if (something === undefined)
这是身份运算符。。。
所有答案都不完整。这是了解存在“定义为未定义”属性的正确方法:
var hasUndefinedProperty = function hasUndefinedProperty(obj, prop){
return ((prop in obj) && (typeof obj[prop] == 'undefined'));
};
例子:
var a = { b : 1, e : null };
a.c = a.d;
hasUndefinedProperty(a, 'b'); // false: b is defined as 1
hasUndefinedProperty(a, 'c'); // true: c is defined as undefined
hasUndefinedProperty(a, 'd'); // false: d is undefined
hasUndefinedProperty(a, 'e'); // false: e is defined as null
// And now...
delete a.c ;
hasUndefinedProperty(a, 'c'); // false: c is undefined
遗憾的是,这是正确的答案,却被错误的答案所掩盖>_<
所以,对于任何路过的人,我会免费给你未定义的!!
var undefined ; undefined ; // undefined
({}).a ; // undefined
[].a ; // undefined
''.a ; // undefined
(function(){}()) ; // undefined
void(0) ; // undefined
eval() ; // undefined
1..a ; // undefined
/a/.a ; // undefined
(true).a ; // undefined
来自lodash.js。
var undefined;
function isUndefined(value) {
return value === undefined;
}
它创建了一个名为undefined的局部变量,该变量用默认值(即真正的undefineed)初始化,然后将该值与变量undefine进行比较。
更新日期:2019年9月9日
我发现Lodash更新了它的实现。查看我的问题和代码。
要做到防弹,只需使用:
function isUndefined(value) {
return value === void 0;
}
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔