9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptで列挙型っぽいことをやる

9
Last updated at Posted at 2013-01-17
enum.js
/**
 *  逆配列を求める(ただし1対1対応限定)
 */
function getEnum(arr) {
  var i;
  var len = arr.length;
  var ret = {};
  for(i=0; i<len; i++) {
    ret[arr[i]] = i;
  }
  return ret;
}

使い方

var magiArr = ["MELCHIOR", "BALTHASAR", "CASPER"];
var magi = getEnum(magiArr);

// 定数の感覚で呼び出す
var a = magi.MELCHIOR; // => 0
var b = magi.BALTHASAR; // => 1
var c = magi.CASPER; // => 2

// 元のキーもわかる
magiArr[a] // => "MELCHIOR"
magiArr[b] // => "BALTHASAR"
magiArr[c] // => "CASPER"

9
7
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?