javascript 在javascript中将int转换为枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24894685/
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-28 03:31:41  来源:igfitidea点击:

Cast int to enum in javascript

javascript

提问by aggaton

How do you efficiently cast an int to enum in javascript?

你如何在 javascript 中有效地将 int 转换为 enum?

Say I have this enum

说我有这个枚举

enuTable = // Table enum
{
    enuUnknown: 0,
    enuPerson: 1,
    enuItem: 2,
    enuSalary: 3,
    enuTax: 4,
    enuZip: 5,
    enuAddress: 6,
    enuLocation: 7,
    enuTasks: 8,

};

In part of the code I get a return value from an AJAX call that is a number corresponding to one of the above tables.

在部分代码中,我从 AJAX 调用中获得一个返回值,该值是与上述表格之一对应的数字。

I can write a switch transforming the value, however is there a more efficient (briefer) way of casting an int to enum? One reason is, I don't want to constantly have to change the switch, in case I change the enum. I guess I could use an array with the enum names and construct an identifier to index into the enum, however again, I would need to change the array every time the enum is changed. I guess what I am looking for is a transparent method, that doesn't require beforehand knowledge of the enum.

我可以编写一个转换值的开关,但是有没有更有效(更简洁)的方法将 int 转换为枚举?一个原因是,我不想经常更改开关,以防我更改枚举。我想我可以使用带有枚举名称的数组并构造一个标识符来索引到枚举中,但是同样,每次更改枚举时我都需要更改数组。我想我正在寻找的是一种透明的方法,不需要事先了解枚举。

回答by Yury Tarabanko

Like this

像这样

var keys = Object.keys(enuTable).sort(function(a, b){
    return enuTable[a] - enuTable[b];
}); //sorting is required since the order of keys is not guaranteed.

var getEnum = function(ordinal) {
    return keys[ordinal];
}

UPD:Is some ordinal values are absent you can use

UPD:是否缺少一些序数值,您可以使用

var keys = Object.keys(enuTable).reduce(function(acc, key) {
    return acc[enuTable[key]] = key, acc;
}, {});

回答by Ben Griffiths

One option would be something like the following:

一种选择类似于以下内容:

 function toTableName(i) {
     for(var p in enuTable) {
         if(enuTable.hasOwnProperty(p) && enuTable[p] === i) {
              return p;
         }
     }
     throw new Error('that\'s no table...');
}

回答by Matías Fidemraizer

First of all, JavaScript doesn't have enumerations like C# has built-in.

首先,JavaScript 没有像 C# 那样内置的枚举。

Thus, I believe that if you receive an AJAX numeric-based identifier and you want to code a switchstatement, you don't need to castto Numberin JavaScript, because your switch will compare your pseudo-enumeration property value:

因此,我相信,如果你收到一个基于AJAX的数字标识符,你想代码switch说法,你不需要Number在JavaScript中,因为你的交换机会比较你的伪枚举属性值:

switch(ajaxNumber) {
   case enuTable.enuPerson: 
      break;
}

If you're looking for obtaining the enumeration value label (for example enuPerson) the following code should be enough (check out a working sample in jsFiddle):

如果您正在寻找获取枚举值标签(例如enuPerson),以下代码应该足够了(查看jsFiddle 中的工作示例):

// We're going to implement a basic enumeration prototype to generalize
// what you're looking for so you may re-use this code anywhere!
function Enum(valueMap) {
    // We store the enumeration object
    this._valueMap = valueMap;
    this._valueToLabelMap = {};
    var that = this;

    // This will create an inverse map: values to labels
    Object.keys(valueMap).forEach(function (label) {
        that._valueToLabelMap[valueMap[label]] = label;
    });
}

Enum.prototype = {
    // Getting the whole label is as simple as accessing
    // the inverse map where values are the object properties!
    getLabel: function (value) {
        if (this._valueToLabelMap.hasOwnProperty(value)) {
            return this._valueToLabelMap[value];
        } else {
            throw Error("Enum instance has no defined '" + value + "' value");
        }
    }
};

var enuTable = new Enum({
    enuUnknown: 0,
    enuPerson: 1,
    enuItem: 2,
    enuSalary: 3,
    enuTax: 4,
    enuZip: 5,
    enuAddress: 6,
    enuLocation: 7,
    enuTasks: 8,
});

// Now, if we provide a number, the fancy Enum prototype will handle it
// so you're going to get the whole enumeration value label!
var taxLabel = enuTable.getLabel(45);

回答by Ro NL

I love Yury Tarabanko's solution, but it took me some time to understand what it does (including reading and understanding about reduce(). I can't comment on you @YuryTarabanko, but how did you come up with this?

我喜欢 Yury Tarabanko 的解决方案,但我花了一些时间来理解它的作用(包括阅读和理解 reduce())。我不能评论你@YuryTarabanko,但你是怎么想出这个的?

The solution I whould come up with, is this one. You can access it the same as Yury's solution (keys[ajaxResponseNumber]). I tested it with jsPerf and this is faster in Firefox, but that's not relevant in this case.

我想出的解决方案就是这个。您可以像 Yury 的解决方案 (keys[ajaxResponseNumber]) 一样访问它。我用 jsPerf 对其进行了测试,这在 Firefox 中速度更快,但在这种情况下无关紧要。

var keys = {}; for (var x in enuTable) { if (enuTable.hasOwnProperty(x)) { keys[enuTable[x]] = x; } }

var keys = {}; for (var x in enuTable) { if (enuTable.hasOwnProperty(x)) { keys[enuTable[x]] = x; } }