LoginSignup
125
125

More than 3 years have passed since last update.

【javascript】処理を分岐させるのにswitch caseを使うのはもう終わりにしよう

Last updated at Posted at 2015-01-28

sensationalなタイトルでごめんなさい。

1. 魅力に欠けるswitch-case

bad
var f = function(v) {
  switch (v) {
    case 'a':
      return 1;
      break;
    case 'b':
      return 2;
      break;
    case 'c':
      return 3;
      break;
  }
};

var v = _.sample(['a', 'b', 'c']);
f(v);

2. アトラクチブな書き方

good
var f = {}
f['a'] = function() {
  return 1;
};
f['b'] = function() {
  return 2;
};
f['c'] = function() {
  return 3;
};

var v = _.sample(['a', 'b', 'c']);
f[v]();

所感

  • 個人的には2のほうが好みです。スコープも切れますし。
125
125
9

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
125
125