如何检查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

如果使用的是Angular:

angular.isUndefined(obj)
angular.isUndefined(obj.prop)

Undercore.js:

_.isUndefined(obj) 
_.isUndefined(obj.prop) 

检查属性值是否为未定义的特殊值的通常方法是:

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`");
}

我在这里为那些希望得到奇怪答案的人提供了三种方法:

函数为Undefined1(val){尝试{值a;}捕获(e){返回/未定义/测试(e.message);}return false;}函数为Undefined2(val){回来val&&val+“”==“未定义”;}函数未定义3(val){常量defaultVal={};return((input=defaultVal)=>input==defaultVal(val);}功能测试(func){console.group(`test start:`+func.name);console.log(func(未定义));console.log(func(null));console.log(函数(1));console.log(函数(“1”));console.log(函数(0));console.log(func({}));console.log(func(函数(){}));console.groupEnd();}测试(isUndefined1);测试(未定义2);测试(未定义3);

未定义1:

尝试获取输入值的属性,并检查错误消息(如果存在)。如果输入值未定义,则错误消息将为Uncaught TypeError:无法读取未定义的属性“b”。

未定义2:

将输入值转换为字符串以与“undefined”进行比较,并确保其为负值。

未定义3:

在JavaScript中,当输入值完全未定义时,可选参数会起作用。

如果你这样做

if (myvar == undefined )
{ 
    alert('var does not exists or is not initialized');
}

当变量myvar不存在时,它将失败,因为没有定义myvar,所以脚本被破坏,测试没有效果。

由于窗口对象在函数外部具有全局作用域(默认对象),因此声明将“附加”到窗口对象。

例如:

var myvar = 'test';

全局变量myvar与window.myvar或window['myvar']相同

为了避免在存在全局变量时要测试的错误,最好使用:

if(window.myvar == undefined )
{ 
    alert('var does not exists or is not initialized');
}

一个变量是否真的存在并不重要,它的值是不正确的。否则,用undefined初始化变量是愚蠢的,最好使用值false来初始化。当你知道你声明的所有变量都是用false初始化的时候,你可以简单地检查它的类型或者依赖它!window.myvar检查它是否具有正确/有效的值。因此,即使没有定义变量!window.myvar对于myvar=undefined或myvar=false或myvar=0是相同的。

如果需要特定类型,请测试变量的类型。要加快测试条件,您最好执行以下操作:

if( !window.myvar || typeof window.myvar != 'string' )
{
    alert('var does not exists or is not type of string');
}

当第一个简单条件为真时,解释器将跳过下一个测试。

最好使用变量的实例/对象来检查它是否获得了有效值。它更稳定,是一种更好的编程方式。

(y)