如何检查JavaScript中的对象属性是否未定义?
当前回答
"propertyName" in obj //-> true | 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
与void 0进行比较,以获得简洁性。
if (foo !== void 0)
它不像(typeoffoo!=='undefined')那样冗长
Use:
要检查属性是否未定义,请执行以下操作:
if (typeof something === "undefined") {
alert("undefined");
}
要检查属性是否未定义,请执行以下操作:
if (typeof something !== "undefined") {
alert("not undefined");
}
您可以像这样使用JavaScript对象函数:
var ojb ={
age: 12
}
if(ojb.hasOwnProperty('name')){
console.log('property exists and is not undefined');
}
如果获得该属性或该属性未定义,则上述方法返回true。
这可能是确定现有属性名称是否具有显式和预期值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