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