如何检查JavaScript中的对象属性是否未定义?
当前回答
如果定义了一个新变量,可以用一种优雅的方式将已定义的属性分配给它;如果未定义,则可以将默认值分配给它作为回退。
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
其他回答
在JavaScript中,存在null和undefined。它们有不同的含义。
undefined表示变量值尚未定义;不知道值是多少。null表示变量值被定义并设置为null(没有值)。
Marijn Haverbeke在他的免费在线书《Eloquent JavaScript》(我的重点)中写道:
还有一个类似的值null,其含义是“此值已定义,但没有值”。undefined和null之间的含义差异主要是学术性的,通常不太有趣。在实际程序中,经常需要检查某个东西是否“有价值”。在这些情况下,可以使用表达式something==undefined,因为即使它们不是完全相同的值,null==undefine也会产生true。
所以,我想最好的检查方法是:
if (something == undefined)
对象财产的工作方式应该相同。
var person = {
name: "John",
age: 28,
sex: "male"
};
alert(person.name); // "John"
alert(person.fakeVariable); // undefined
if (somevariable == undefined) {
alert('the variable is not defined!');
}
您也可以将其转换为函数,如下所示:
function isset(varname){
return(typeof(window[varname]) != '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方法
读到这里,我很惊讶我没有看到这一点。我已经找到了多种算法可以解决这个问题。
从未定义
如果从未定义对象的值,那么如果将其定义为null或undefined,则将无法返回true。如果您希望为设置为undefined的值返回true,这很有用
if(obj.prop === void 0) console.log("The value has never been defined");
定义为未定义或从未定义
如果您希望使用undefined值定义的值或从未定义的值的结果为true,则可以简单地使用==undefineed
if(obj.prop === undefined) console.log("The value is defined as undefined, or never defined");
定义为错误值、未定义、空或从未定义。
通常,人们要求我提供一种算法,以确定某个值是否为假值、未定义值或空值。以下工作。
if(obj.prop == false || obj.prop === null || obj.prop === undefined) {
console.log("The value is falsy, null, or undefined");
}
句柄未定义
function isUndefined(variable,defaultvalue=''){
if (variable == undefined ) return defaultvalue;
return variable;
}
变量obj={und:未定义,notundefined:“我没有定义”}函数isUndefined(变量,默认值=“”){if(变量==未定义){ 返回默认值;}返回变量}console.log(is未定义(obj.und,'i am print'))console.log(isUndefined(obj.notundefined,'Iam print'))