我应该如何将现有的 Javascript 枚举映射到相应的字符串值?
因此,我在页面的 javascript 中添加了以下内容:
var TEST_ERROR = {
'SUCCESS' : 0,
'FAIL' : -1,
'ID_ERROR' : -2
};
并对页面中的函数执行测试,如下所示:
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;
}
testCalculate()
的结果和段落的值将为 0、-1、- 2 取决于结果。
现在我想将其映射到一个字符串,以便该段落显示“成功”、“失败”或“ID 错误”
我可以通过我想到的几种方法来做到这一点:
var TEST_ERROR = {
'SUCCESS' : {VALUE : 0 , STRING: 'Success' },
'FAIL' : {VALUE : -1, STRING: 'Fail' },
'ID_ERROR' : {VALUE : -2, STRING: 'Id Error'},
};
需要修改枚举点访问器,或者
var TEST_ERROR = {
'SUCCESS' : 0,
'FAIL' : 1,
'ID_ERROR' : 2
};
var TEST_STRING = [
'Success',
'Fail',
'ID Error'
];
哪一个会需要更改逻辑(结果 > TEST_ERROR.SUCCESS
看起来很奇怪!)
我的问题是如何将枚举值映射到 Javascript 中的字符串值?我认为第二种方法是最明智的,但希望枚举器对于成功为正,对于失败为负。我也喜欢第一个在对象结构中包含字符串和值的想法。
有什么想法吗?
谢谢!
马特
PS.我将在 Web Worker 中进行测试,这样页面就不会挂起,并且结果将放入表格中,而不是像上面那样的段落中。
PPS。我对 Javascript 编程还很陌生,但在 ASM、C、C++、C# 方面做了很多工作。
So I have this in the javascript for my page:
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.
Now I want to map this to a string so that the paragraph shows 'Success', 'Fail' or 'ID Error'
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!)
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.
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.
PPS. I'm pretty new to Javascript programming, but do a lot in ASM, C, C++, C#.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
基于 Victor 的出色答案,因此它可以在 TypeScript 中使用:
Building on Victor's excellent answer, so it works in TypeScript:
如果您是打字稿,那么您已经有了枚举的定义。否则你可以直接使用 JS 版本的枚举。
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.
最好的方法是:
我们需要添加冻结,即使
UserLevel
是const
,因为我们可以更改里面的值。freeze
将使“枚举”免受更改。The best way to do it is:
We need to add freeze, even though
UserLevel
isconst
, because we can change the values inside.freeze
will make the "enum" safe from changes.这可能与您想要的不同,但我想分享我的答案。这是受到@LukeHconst 解决方案的启发。考虑下面的
bookCategory
,您会注意到我使用数字作为键。我这样写了
bookCategory
因为如果你在 MySQL 中使用枚举列。例如,您需要在 JavaScript 中进行某种转换。所以我想出了这个,用法很简单:
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.I wrote the
bookCategory
like this because if you are using an enum column in MySQL. For example,You would need some kind of conversion in JavaScript. So I came up with this and the usage is simple as:
如果您使用 TypeScript 并且不需要数值,则可以直接映射到字符串值,如下所示:
来源:https://www.typescriptlang.org/docs/handbook/enums.html#string-enums
If you're using TypeScript and don't need the numeric values, you can map directly to string values like this:
Source: https://www.typescriptlang.org/docs/handbook/enums.html#string-enums
其他答案无法解决枚举是复合词(如 InProgress)并且您希望将其转换为常量(进行中)以保持枚举中的数字索引的情况。
这个答案有更多细节
当我想在用户界面中正确显示这个枚举时,我需要这个场景。对用户有意义的英文文本。
Other answers fail to address a scenario where the Enum is a compound word(like InProgress) and you want to convert it to constant(In Progress) keeping the number indexing in enum.
This answer has more details
I needed this scenario when I wanted to show this enum in the UI as proper & meaningful English text to user.
对于 TypeScript,有一个更简单的解决方案
(如果你坚持使用JS,请忽略我的回答):
因为枚举类型被编译成对象(字典)。
您不需要循环来查找相应的值。
被编译为:
For TypeScript, there is a simpler solution
(Please ignore my answer if you stick with JS):
Because the enumeration type is compiled into an object(dictionary).
You don't need a loop to find the corresponding value.
is compiled into:
我更喜欢下面的方法。
I prefer the below method.
您始终可以将值设为特定类型的对象。
现在,当您获取该类型的值时:
您可以使用以下方式获取字符串值
。事实上,大多数时候您甚至不必显式调用
.toString()
。You could always have the values be objects of a particular type.
Now when you get a value of that type:
you can get the string value with
In fact you shouldn't even have to call
.toString()
explicitly, most of the time.您真的需要这些数值吗?如果没有那么你可以使用这样的东西:
Do you actually need the numeric values at all? If not then you could use something like this:
不太理想,但在不预先计算反向字典的情况下可以获得最干净的结果(此外,如果您只有几个枚举值,这不应该是一个太大的问题):
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):