如何检查JavaScript中的对象属性是否未定义?
当前回答
我很惊讶我还没有看到这个建议,但它比使用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
}
其他回答
我很惊讶我还没有看到这个建议,但它比使用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
}
我没有看到(希望我没有错过)任何人在物业前检查该对象。因此,这是最短和最有效的(虽然不一定是最清楚的):
if (obj && obj.prop) {
// Do something;
}
如果obj或obj.prop为undefined、null或“falsy”,If语句将不执行代码块。这通常是大多数代码块语句(在JavaScript中)所需的行为。
更新:(2021 7月2日)
最新版本的JavaScript为可选链接:?。
这可能是检查对象财产是否存在的最明确、最有效的方法。
裁判:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
这可能是确定现有属性名称是否具有显式和预期值undefined的唯一显式形式;尽管如此,这是一种JavaScript类型。
"propertyName" in containerObject && ""+containerObject["propertyName"] == "undefined";
>> true \ false
仅当给定上下文的属性名存在(真实存在)并且其预期值未明确定义时,此表达式才会返回true。
不会出现假阳性,例如空字符串、空字符串、零、空数组等。这正是如此。检查,即确保属性名存在(否则将为假阳性),然后显式检查其值是否未定义,例如其字符串表示形式中的未定义JavaScript类型(字面上为“undefined”),因此==而不是==,因为无法进行进一步转换。只有满足这两个条件,这个表达式才会返回true。例如,如果属性名称不存在,则返回false。这是唯一正确的返回,因为不存在的财产不能有值,甚至不能有未定义的值。
例子:
containerObject = { propertyName: void "anything" }
>> Object { propertyName: undefined }
// Now the testing
"propertyName" in containerObject && ""+containerObject["propertyName"] == "undefined";
>> true
/* Which makes sure that nonexistent property will not return a false positive
* unless it is previously defined */
"foo" in containerObject && ""+containerObject["foo"] == "undefined";
>> false
使用动态变量的版本你知道吗?
var boo='Ala';函数检查(){if(this['fo']){console.log('o is here');}其他{console.log('没有foo');}如果(这个['bo']){console.log('boo在这里');}其他{console.log('没有boo');}}check();
我想向您展示我正在使用的一些东西,以保护未定义的变量:
Object.defineProperty(window, 'undefined', {});
这禁止任何人更改window.undefined值,从而破坏基于该变量的代码。如果使用“usestrict”,任何试图更改其值的行为都将以错误告终,否则将被忽略。