Skip to content

Instantly share code, notes, and snippets.

@t-uda
Created April 25, 2014 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t-uda/11292346 to your computer and use it in GitHub Desktop.
Save t-uda/11292346 to your computer and use it in GitHub Desktop.
switch(true) イディオム考察 ref: http://qiita.com/t_uda/items/1969e09a970d71e4cfd6
もし条件 condition が成り立つならば hoge する.
expr の評価結果によって場合分けする.
A の場合は,hoge する.
B の場合は,fuga する.
true の評価結果(??)によって場合分けする.
x < 0 の場合は,hoge する.
x === 0 の場合は,fuga する.
x > 0 の場合は,piyo する.
function hoge(x) {
if (x < 0) {
console.log(x + " は自然数ではありません.");
} else if (x === 0) {
console.log("ここでは 0 は自然数です.");
} else if (x > 0) {
console.log(x + " は正の数です.");
} else {
console.log(x + " は数ではないようです.");
}
}
function hoge(x) {
switch (true) {
case x < 0:
console.log(x + " は自然数ではありません.");
break;
case x === 0:
console.log("ここでは 0 は自然数です.");
break;
case x > 0:
console.log(x + " は正の数です.");
break;
default:
console.log(x + " は数ではないようです.");
}
}
(function () {
// local scope
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment