如何检查开关主体是否为客体



我的Ajax响应可以是json object, bool或各种string values

我可以检查它是否是switch语句中的对象吗?

$.post('url',{some:'data'},function(response){
   switch (response){
   case true:
     console.log('is true');
     break;
   case false:
     console.log('is false');
     break;
   case 'success':
     console.log('is success');
     break;
   case typeof this === 'object' // thought I'd try this but it didn't work.
     console.log('is object');
     break;
   }
});

switch执行参数与case表达式之间的相等比较。因此,case typeof this === 'object'计算typeof this === 'object'的值,这将是truefalse,这取决于this是什么(它将是window),并将其与response进行比较。它不会测试response的类型如果你想切换response的类型,使用它作为参数。

试题:

switch (typeof response) {
case 'boolean':
    if (response) {
        console.log('is true');
    } else {
        console.log('is false');
    }
    break;
case 'string':
    if (response == 'success') {
        console.log('is success');
    } else {
        // do something
    }
    break;
case 'object':
    console.log('is object');
    break;
}

一般来说,当你想对同一个值做一系列相等性测试时,应该使用switch。你不能在同一个switch中混合使用等式和类型测试;您需要使用switch为一个,if为另一个。

设置默认大小写:

default : 
     if(typeof response === 'object'){ // thought I'd try this but it didn't work.
     console.log('is object');
     }
     break;

最新更新