如何检查JavaScript中的对象属性是否未定义?
当前回答
这可能是确定现有属性名称是否具有显式和预期值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 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 (somevariable == undefined) {
alert('the variable is not defined!');
}
您也可以将其转换为函数,如下所示:
function isset(varname){
return(typeof(window[varname]) != 'undefined');
}
您可以像这样使用JavaScript对象函数:
var ojb ={
age: 12
}
if(ojb.hasOwnProperty('name')){
console.log('property exists and is not undefined');
}
如果获得该属性或该属性未定义,则上述方法返回true。
我很惊讶我还没有看到这个建议,但它比使用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
}
在ECMAScript 6中引入,我们现在可以使用代理以一种新的方式处理未定义。它可以用于为任何不存在的财产设置默认值,这样我们就不必每次都检查它是否实际存在。
var handler = {
get: function(target, name) {
return name in target ? target[name] : 'N/A';
}
};
var p = new Proxy({}, handler);
p.name = 'Kevin';
console.log('Name: ' +p.name, ', Age: '+p.age, ', Gender: '+p.gender)
将输出以下文本而不会得到任何未定义。
Name: Kevin , Age: N/A , Gender: N/A