0
次のようなswitch文を使用できますか?Javascriptスイッチ未定義のプロパティ
switch(this.myObject && this.myObject.myProperty){ //... }
myObjectが定義されているかどうかをテストする目的ですか?
次のようなswitch文を使用できますか?Javascriptスイッチ未定義のプロパティ
switch(this.myObject && this.myObject.myProperty){ //... }
myObjectが定義されているかどうかをテストする目的ですか?
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';
はい、それが可能です。虚偽の場合、値は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} }));
それは '場合は未定義で動作します:'が、スイッチが厳格であることを覚えています。 –
「if」だけではないのはなぜですか? – melancia
この場合、単純に2つのケースがあります - ケース '真'、ケース '偽'? –