JavaScript的switch...case语句,是在开发中经常用到的,但是通常都是给定值,然后进入case分支的操作,今天来总结一些switch
的其他操作。
用 Switch 重写多个 If 语句
var a = 100;
var b = NaN;
switch (true) {
case isNaN(a) || isNaN(b):
console.log('NaNNaN');
break;
case a === b:
console.log(0);
break;
case a < b:
console.log(-1);
break;
default:
console.log(1);
}
// NaNNaN
多case,单操作
var Animal = 'Giraffe';
switch (Animal) {
case 'Cow':
case 'Giraffe':
case 'Dog':
case 'Pig':
console.log('This animal will go on Noah\'s Ark.');
break;
case 'Dinosaur':
default:
console.log('This animal will not.');
}
// This animal will go on Noah's Ark.