Javascript打开未定义的属性

时间:2016-06-21 12:30:51

标签: javascript

是否可以使用如下所示的开关语句?

switch(this.myObject && this.myObject.myProperty){ //... }

目的是测试是否定义了myObject?

2 个答案:

答案 0 :(得分:0)

if (typeof this.myObject !== 'undefined' && typeof this.myObject.myProperty !== 'undefined') {
    switch(this.myObject.myProperty) {
        //...
    }
} else {
    //don't exist
}

或:

var objectAndPropertyExists = typeof this.myObject !== 'undefined' && typeof this.myObject.myProperty !== 'undefined';

答案 1 :(得分:0)

是的,这是可能的。请注意,在虚假案例中,价值可能来自this.myObjectthis.myObject.myProperty

function f() {
  switch(this.myObject && this.myObject.myProperty){
    case undefined: return 'myObject or myProperty are undefined';
    case 123: return 'myProperty is 123';
    default: return 'something else';
  }
}
console.log(f.call({}));
console.log(f.call({myObject: true }));
console.log(f.call({myObject: false }));
console.log(f.call({myObject: {myProperty:123} }));
console.log(f.call({myObject: {myProperty:456} }));
console.log(f.call({myObject: {myProperty:undefined} }));