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.


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM