如何检查JavaScript中的对象属性是否未定义?
当前回答
同样的事情也可以写得更短:
if (!variable){
// Do it if the variable is undefined
}
or
if (variable){
// Do it if the variable is defined
}
其他回答
if (somevariable == undefined) {
alert('the variable is not defined!');
}
您也可以将其转换为函数,如下所示:
function isset(varname){
return(typeof(window[varname]) != 'undefined');
}
在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
所有答案都不完整。这是了解存在“定义为未定义”属性的正确方法:
var hasUndefinedProperty = function hasUndefinedProperty(obj, prop){
return ((prop in obj) && (typeof obj[prop] == 'undefined'));
};
例子:
var a = { b : 1, e : null };
a.c = a.d;
hasUndefinedProperty(a, 'b'); // false: b is defined as 1
hasUndefinedProperty(a, 'c'); // true: c is defined as undefined
hasUndefinedProperty(a, 'd'); // false: d is undefined
hasUndefinedProperty(a, 'e'); // false: e is defined as null
// And now...
delete a.c ;
hasUndefinedProperty(a, 'c'); // false: c is undefined
遗憾的是,这是正确的答案,却被错误的答案所掩盖>_<
所以,对于任何路过的人,我会免费给你未定义的!!
var undefined ; undefined ; // undefined
({}).a ; // undefined
[].a ; // undefined
''.a ; // undefined
(function(){}()) ; // undefined
void(0) ; // undefined
eval() ; // undefined
1..a ; // undefined
/a/.a ; // undefined
(true).a ; // undefined
如果定义了一个新变量,可以用一种优雅的方式将已定义的属性分配给它;如果未定义,则可以将默认值分配给它作为回退。
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
function isUnset(inp) {
return (typeof inp === 'undefined')
}
如果变量已设置,则返回false;如果未定义,则返回true。
然后使用:
if (isUnset(var)) {
// initialize variable here
}