如何检查JavaScript中的对象属性是否未定义?
当前回答
与void 0进行比较,以获得简洁性。
if (foo !== void 0)
它不像(typeoffoo!=='undefined')那样冗长
其他回答
在JavaScript中,有truthy和falsy表达式。如果要检查属性是否未定义,可以直接使用给定的If条件,
使用真/假概念。
if(!ob.someProp){
console.log('someProp is falsy')
}
然而,还有几种方法可以检查对象是否具有属性,但对我来说似乎很长。
使用==未定义的签入if条件
if(ob.someProp === undefined){
console.log('someProp is undefined')
}
使用的类型
typeof充当未定义值和变量是否存在的组合检查。
if(typeof ob.someProp === 'undefined'){
console.log('someProp is undefined')
}
使用hasOwnProperty方法
JavaScript对象已在对象原型中的hasOwnProperty函数中构建。
if(!ob.hasOwnProperty('someProp')){
console.log('someProp is undefined')
}
不深入,但第一种方法看起来很短,对我来说很好。下面是JavaScript中truthy/falsy值的详细信息,未定义的是其中列出的falsy。所以if条件的行为正常,没有任何故障。除了未定义的值之外,值NaN、false(显然)、“”(空字符串)和数字0也是假值。
警告:请确保属性值不包含任何错误值,否则if条件将返回false。对于这种情况,可以使用hasOwnProperty方法
检查属性值是否为未定义的特殊值的通常方法是:
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`");
}
使用动态变量的版本你知道吗?
var boo='Ala';函数检查(){if(this['fo']){console.log('o is here');}其他{console.log('没有foo');}如果(这个['bo']){console.log('boo在这里');}其他{console.log('没有boo');}}check();
同样的事情也可以写得更短:
if (!variable){
// Do it if the variable is undefined
}
or
if (variable){
// Do it if the variable is defined
}
我很惊讶我还没有看到这个建议,但它比使用typeof测试更具特异性。如果您需要知道对象属性是用undefined初始化的还是从未初始化过,请使用Object.getOwnPropertyDescriptor():
// to test someObject.someProperty
var descriptor = Object.getOwnPropertyDescriptor(someObject, 'someProperty');
if (typeof descriptor === 'undefined') {
// was never initialized
} else if (typeof descriptor.value === 'undefined') {
if (descriptor.get || descriptor.set) {
// is an accessor property, defined via getter and setter
} else {
// is initialized with `undefined`
}
} else {
// is initialized with some other value
}
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔