Javascript 枚举到相应的字符串值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4286899/
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
Javascript Enum To Corresponding String Value
提问by Matt Clarkson
So I have this in the javascript for my page:
所以我在我的页面的javascript中有这个:
var TEST_ERROR = {
'SUCCESS' : 0,
'FAIL' : -1,
'ID_ERROR' : -2
};
And perform tests on functions in the page like so:
并对页面中的函数执行测试,如下所示:
function test()
{
// Get the paragraph from the DOM
var testResultParagraph = document.getElementById('testResult');
// Check the paragraph is valid
if(!testResultBox)
{
// Update the web page
testResultParagraph.value = TEST_ERROR.ID_ERROR;
return TEST_ERROR.ID_ERROR;
}
// Something to store the results
var testResult = TEST_ERROR.SUCCESS;
// Test the calculation
testResult = testCalculate()
// Update the web page
testResultParagraph.value = testResult;
// The test succeeded
return TEST_ERROR.SUCCESS;
}
The result of testCalculate()
and the value of the paragraph will be either 0, -1, -2 depending on the outcome.
testCalculate()
段落的结果和值将是 0、-1、-2,具体取决于结果。
Now I want to map this to a string so that the paragraph shows 'Success', 'Fail' or 'ID Error'
现在我想将其映射到一个字符串,以便该段落显示“成功”、“失败”或“ID 错误”
I could do this a few ways I have figured:
我可以通过几种方法来做到这一点:
var TEST_ERROR = {
'SUCCESS' : {VALUE : 0 , STRING: 'Success' },
'FAIL' : {VALUE : -1, STRING: 'Fail' },
'ID_ERROR' : {VALUE : -2, STRING: 'Id Error'},
};
would require a modification to the enum dot accessors, or
需要修改枚举点访问器,或
var TEST_ERROR = {
'SUCCESS' : 0,
'FAIL' : 1,
'ID_ERROR' : 2
};
var TEST_STRING = [
'Success',
'Fail',
'ID Error'
];
Which would require changes to the logic (result > TEST_ERROR.SUCCESS
seems wierd tho!)
这需要更改逻辑(result > TEST_ERROR.SUCCESS
似乎很奇怪!)
My question is how would you go about mapping an enumerator value to a string value in Javascript?I'm thinking the second way is the most sensible, but would like the enumerator to be positive for successes and negative for fails. I also like the idea of the first containing the strings and values in the object structure.
我的问题是您将如何将枚举值映射到 Javascript 中的字符串值?我认为第二种方式是最明智的,但希望枚举器对成功表示积极,对失败表示消极。我也喜欢第一个在对象结构中包含字符串和值的想法。
Any ideas?
有任何想法吗?
Thanks!
谢谢!
Matt
马特
PS. I'm going to be doing the testing in a Web Worker, so that the page doesn't hang and the results will be put into a table, not a paragraph like above.
附注。我将在 Web Worker 中进行测试,以便页面不会挂起并且结果将放入表格中,而不是像上面那样的段落。
PPS. I'm pretty new to Javascript programming, but do a lot in ASM, C, C++, C#.
聚苯乙烯。我对 Javascript 编程很陌生,但在 ASM、C、C++、C# 方面做了很多工作。
采纳答案by LukeH
Do you actually need the numeric values at all? If not then you could use something like this:
你真的需要数值吗?如果没有,那么你可以使用这样的东西:
var TEST_ERROR = {
SUCCESS : 'Success',
FAIL : 'Fail',
ID_ERROR : 'ID Error'
};
回答by Victor Nicollet
Not quite optimal, but the cleanest you can get without pre-computing the reverse dictionary (and besides, this shouldn't be too much of an issue if you only have a few enumeration values):
不是很理想,但无需预先计算反向字典即可获得最干净的结果(此外,如果您只有几个枚举值,这应该不是什么大问题):
function string_of_enum(enum,value)
{
for (var k in enum) if (enum[k] == value) return k;
return null;
}
回答by Pointy
You could always have the values be objects of a particular type.
您可以始终将值设为特定类型的对象。
var TEST_ERROR = (function() {
function ErrorValue(value, friendly) {
this.value = value;
this.friendly = friendly;
}
ErrorValue.prototype = {
toString: function() { return this.friendly; },
valueOf: function() { return this.value; }
};
return {
'SUCCESS': new ErrorValue(0, 'Success'),
'FAIL': new ErrorValue(1, 'Fail'),
'ID_ERROR': new ErrorValue(2, 'ID error')
};
})();
Now when you get a value of that type:
现在,当您获得该类型的值时:
var err = testFunction(whatever);
you can get the string value with
你可以得到字符串值
alert(err.toString());
In fact you shouldn't even have to call .toString()
explicitly, most of the time.
事实上.toString()
,大多数情况下,您甚至不必显式调用。
回答by Pratik Bhattacharya
If you are typescript, then you will already have a definition for the enum. Else you can directly use the JS version of the enum.
如果你是打字稿,那么你已经有了枚举的定义。否则你可以直接使用枚举的 JS 版本。
var Status;
(function (Status) {
Status[Status["New"] = 0] = "New";
Status[Status["Submitted"] = 1] = "Submitted";
Status[Status["Approved"] = 2] = "Approved";
Status[Status["Rejected"] = 3] = "Rejected";
})(Status || (Status = {}));
var snew = Status.New;
console.log(snew); //This is the number
console.log(Status[snew]); //This is the string
回答by Idan
The best way to do it is:
最好的方法是:
export const UserLevel = Object.freeze({
BABY: 1,
CHILED: 2
});
Why we need to add freeze UserLevel is const but we can change the values inside, so freeze will make it safe for changes.
为什么我们需要添加 freeze UserLevel 是 const 但我们可以更改其中的值,因此 freeze 将使其安全更改。
回答by Zhaolin Feng
For TypeScript, there is a simpler solution (Please ignore my answer if you stick with JS):
对于 TypeScript,有一个更简单的解决方案(如果你坚持使用 JS,请忽略我的回答):
export enum Direction {
none,
left = 1,
right = 2,
top = 4,
bottom = 8
}
export namespace Direction {
export function toString(dir: Direction): string {
return Direction[dir];
}
export function fromString(dir: string): Direction {
return (Direction as any)[dir];
}
}
console.log("Direction.toString(Direction.top) = " + Direction.toString(Direction.top));
// Direction.toString(Direction.top) = top
console.log('Direction.fromString("top") = ' + Direction.fromString("top"));
// Direction.fromString("top") = 4
console.log('Direction.fromString("xxx") = ' + Direction.fromString("unknown"));
// Direction.fromString("xxx") = undefined
Because the enumeration type is compiled into an object(dictionary). You don't need a loop to find the corresponding value.
因为枚举类型被编译成一个对象(字典)。您不需要循环来查找相应的值。
enum Direction {
left,
right
}
is compiled into:
编译成:
{
left: 0
right: 1
0: "left",
1: "right"
}
回答by Storage Lenovo
This might be different from what you want but I want to share my answer. This was inspired by @LukeHconst solution. Consider bookCategory
below you will notice that I'm using a number as a key.
这可能与您想要的不同,但我想分享我的答案。这受到@LukeHconst 解决方案的启发。考虑bookCategory
下面,您会注意到我使用数字作为键。
const bookCategory = {
"0": "Biography",
"1": "Fiction",
"2": "History",
"3": "Mystery",
"4": "Suspense",
"5": "Thriller"
};
I wrote the bookCategory
like this because if you are using an enum column in MySQL. For example,
我这样写是bookCategory
因为如果您在 MySQL 中使用枚举列。例如,
category ENUM ('0', '1', '2', '3', '4', '5')
You would need some kind of conversion in JavaScript. So I came up with this and the usage is simple as:
您需要在 JavaScript 中进行某种转换。所以我想出了这个,用法很简单:
bookCategory[book.category]
回答by Mark Miller
Building on Victor's excellent answer, so it works in TypeScript:
基于 Victor 的优秀答案,因此它适用于 TypeScript:
enumToStr(enumeration: any, value: any): string {
for (var k in enumeration)
if (enumeration[k] == value)
return <string>k;
return null;
}