2016-06-21 16 views
0

次のようなswitch文を使用できますか?Javascriptスイッチ未定義のプロパティ

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

myObjectが定義されているかどうかをテストする目的ですか?

+1

それは '場合は未定義で動作します:'が、スイッチが厳格であることを覚えています。 –

+0

「if」だけではないのはなぜですか? – melancia

+0

この場合、単純に2つのケースがあります - ケース '真'、ケース '偽'? –

答えて

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'; 
0

はい、それが可能です。虚偽の場合、値はthis.myObjectまたはthis.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} }));

関連する問題