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.
