JavaScript 枚举器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6346766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:21:24  来源:igfitidea点击:

JavaScript enumerator?

javascript

提问by wong2

I want to define a list of constants that have continuous integer value, for example:

我想定义一个具有连续整数值的常量列表,例如:

var config.type = {"RED": 0, "BLUE" : 1, "YELLO" : 2};  

But it's boring to add a "XX" : yevery time I need to add a new element in it.
So I'm wondering is there something like enumeratorin C so I can just write:
var config.type = {"RED", "BLUE", "YELLO"}and they are given unique integer value automatically.

但是"XX" : y每次需要在其中添加新元素时都添加一个很无聊。
所以我想知道enumerator在 C 中有没有类似的东西,所以我可以写:
var config.type = {"RED", "BLUE", "YELLO"}并且它们会自动获得唯一的整数值。

回答by Locksfree

You could also try to do something like this:

你也可以尝试做这样的事情:

function Enum(values){
    for( var i = 0; i < values.length; ++i ){
        this[values[i]] = i;
    }
    return this;
}
var config = {};
config.type = new Enum(["RED","GREEN","BLUE"]);
// check it: alert( config.type.RED );

or even using the arguments parameter, you can do away with the array altogether:

甚至使用 arguments 参数,您可以完全取消数组:

function Enum(){
    for( var i = 0; i < arguments.length; ++i ){
        this[arguments[i]] = i;
    }
    return this;
}
var config = {};
config.type = new Enum("RED","GREEN","BLUE");
// check it: alert( config.type.RED );

回答by Naftali aka Neal

Just use an array:

只需使用一个数组:

var config.type =  ["RED", "BLUE", "YELLO"];

config.type[0]; //"RED"

回答by Marc B

Use an array ([]) instead of an object ({}), then flip the array to swap keys/values.

使用数组 ( []) 而不是对象 ( {}),然后翻转数组以交换键/值。

回答by user113716

I suppose you could make a function that accepts an Array:

我想你可以制作一个接受数组的函数:

function constants( arr ) {

    for( var i = 0, len = arr.length, obj = {}; i < len; i++ ) {
        obj[ arr[i] ] = i;
    }
    return obj;
}


var config.type = constants( ["RED", "BLUE", "YELLO"] );

console.log( config.type );  // {"RED": 0, "BLUE" : 1, "YELLO" : 2}


Or take the same function, and add it to Array.prototype.

或者把同样的函数,加入到Array.prototype中。

Array.prototype.constants = function() {

    for( var i = 0, len = this.length, obj = {}; i < len; i++ ) {
        obj[ this[i] ] = i;
    }
    return obj;
}


var config.type = ["RED", "BLUE", "YELLO"].constants();

console.log( config.type );  // {"RED": 0, "BLUE" : 1, "YELLO" : 2}

回答by Darlan Dieterich

Define the Enum:

定义枚举:

var type = {
  RED: 1,
  BLUE: 2, 
  YELLO: 3 
};

get the color:

获取颜色:

var myColor = type.BLUE;