LoginSignup
36

More than 5 years have passed since last update.

初心者によく教えるswitch文のイディオム

Last updated at Posted at 2013-01-18

補足情報がコメント欄にあるので、参考にしてください。

何回か聞かれたので残しておきます。
switchの条件式をtrueにすれば、複雑な条件分岐もスッキリ書けます。
同じように条件式にtrueを入れたら使える言語が他にもあるので覚えておくといいと思います。
ただし、各条件の処理ごとにbreakが必要な言語もあるので、注意してください。
下記は、coffeescriptの例です。

coffeescript_switch_true
switch true
    when a > 5
        console.log "a > 5"
    when b < 3
        console.log "b < 3"
    when c is 4
        console.log "c is 4"
```ちなみに、上記のcsjsにコンパイルすると、下記のようになります。

```javascript:javascript_switch_true
switch (true) {
  case a > 5:
    console.log("a > 5");
    break;
  case b < 3:
    console.log("b < 3");
    break;
  case c === 4:
    console.log("c is 4");
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36