JavaScript中switch语句的用法总结
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.
版权声明:本文为yanshanketang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。