Javascript对象枚举语法

时间:2015-06-01 04:40:12

标签: javascript

我有这个对象:

var State = {
  WAITING: 1,
  READY: 2
}

此对象用于获取州的文本:

var Language = {
  States: {
    WAITING: "Waiting..",
    READY: "Ready!"
  }
}

我想直接从州获取文字:

var state = State.READY;

var statusText = Language.States[state];

为了这个工作,我需要这样的非法语法:

var Language = {
  States: {
    State.WAITING: "Waiting..",
    State.READY: "Ready!"
  }
}

但这不起作用,我可以用什么来简单地从状态变量中获取文本?

3 个答案:

答案 0 :(得分:1)

不,你没有。只是让你的价值观变得明智而不是神奇的数字。在这种情况下,让他们使用映射到您的其他对象使用的键名的字符串,并完成:

var States = {
  WAITING: "WAITING",
  READY: "READY"
}

var Language = {
  States: {
    WAITING: "Waiting..",
    READY: "Ready!"
  }
}

瞧:

var state = States.WAITING;
var label = Language.States[state]

如果那些状态数字意味着什么,那么也要查找它们:

var responseCodes = {
  "0": "WAITING",
  "1": "READING",
  "403": "FORBIDDEN",
  ...
}

然后链接您的查找:

...
var responseCode = whatever();
var state = responseCodes[responseCode];
var label = Language.State[state];
...

答案 1 :(得分:1)

您可能来自语言背景,其中枚举是表示整数值的名称的集合。 JS在枚举值中使用字符串更容易,然后您可以直接将它们用作查找哈希值的键,或者直接在switch语句中使用它们,因此您不需要{{1根本就是变量。你所需要的只是

State

答案 2 :(得分:1)

试试这个:

var State = {
  WAITING: 1,
  READY: 2
};

var Language = {
  States: {}
};

Language.States[State.WAITING] = "Waiting..";
//evaluated as, Language.States[1] = "Waiting..";
Language.States[State.READY] = "Ready!";

var state = State.READY;

var statusText = Language.States[state];

alert(statusText);