我的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'
的值,这将是true
或false
,这取决于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;