如何检查JavaScript中的对象属性是否未定义?
当前回答
所有答案都不完整。这是了解存在“定义为未定义”属性的正确方法:
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
其他回答
如果定义了一个新变量,可以用一种优雅的方式将已定义的属性分配给它;如果未定义,则可以将默认值分配给它作为回退。
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
我想向您展示我正在使用的一些东西,以保护未定义的变量:
Object.defineProperty(window, 'undefined', {});
这禁止任何人更改window.undefined值,从而破坏基于该变量的代码。如果使用“usestrict”,任何试图更改其值的行为都将以错误告终,否则将被忽略。
同样的事情也可以写得更短:
if (!variable){
// Do it if the variable is undefined
}
or
if (variable){
// Do it if the variable is defined
}
function isUnset(inp) {
return (typeof inp === 'undefined')
}
如果变量已设置,则返回false;如果未定义,则返回true。
然后使用:
if (isUnset(var)) {
// initialize variable here
}
Lodash库中有几个小助手:
isUndefined-检查值是否未定义。
_.isUndefined(undefined) // => true
_.isUndefined(null) // => false
has-检查对象是否包含属性
const object = { 'a': { 'b': 2 } }
_.has(object, 'a.b') // => true
_.has(object, 'a.c') // => false
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔