如何检查JavaScript中的对象属性是否未定义?
当前回答
我认为这个问题有很多不正确的答案。与通常的看法相反,“undefined”在JavaScript中不是关键字,实际上可以为其赋值。
正确的代码
执行此测试的最可靠方法是:
if (typeof myVar === "undefined")
这将始终返回正确的结果,甚至可以处理未声明myVar的情况。
退化代码。不要使用。
var undefined = false; // Shockingly, this is completely legal!
if (myVar === undefined) {
alert("You have been misled. Run away!");
}
此外,myVar==undefined将在未声明myVar的情况下引发错误。
其他回答
检查属性值是否为未定义的特殊值的通常方法是:
if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
要检查对象是否实际上没有这样的属性,并且当您尝试访问它时,默认情况下会返回undefined:
if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
要检查与标识符关联的值是否为未定义的特殊值,或者该标识符是否尚未声明:
if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
注意:最后一个方法是引用未声明的标识符而不出现早期错误的唯一方法,这与值为undefined不同。
在ECMAScript 5之前的JavaScript版本中,全局对象上名为“undefined”的属性是可写的,因此,如果不小心重新定义了foo==undefineed,则简单的检查可能会出现意外的行为。在现代JavaScript中,属性是只读的。
然而,在现代JavaScript中,“undefined”不是关键字,因此函数内部的变量可以命名为“undefine”,并隐藏全局属性。
如果您担心这种(不太可能的)边缘情况,可以使用void运算符获取特殊的未定义值本身:
if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
if ( typeof( something ) == "undefined")
这对我有用,而其他人没有。
在《探索JavaScript中的空和未定义的深渊》一文中,我看到Undercore.js等框架使用了这个函数:
function isUndefined(obj){
return obj === void 0;
}
Object.hasOwnProperty(o,'propertyname');
然而,这并不能通过原型链进行查找。
如果定义了一个新变量,可以用一种优雅的方式将已定义的属性分配给它;如果未定义,则可以将默认值分配给它作为回退。
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