我正在尝试从该枚举中获取值:
zed <- zed %>%
dplyr::mutate(newCol = ifelse(possessionName[2:length(possessionName)] != possessionName[1:(length(possessionName)-1)], 1, 0))
使用其他StackOverflows中建议的以下代码,我得到以下输出:
enum Sizes {
Tiny = "Tiny",
VerySmall = "Very Small",
Small = "Small",
Medium = "Medium",
Large = "Large",
VeryLarge = "Very Large"
}
var text=""
for (var size in Sizes) {
text = text + "\n" + size;
}
console.log(text);
我不希望输入VerySmall和VeryLarge,为什么会出现这些以及如何获得所需的结果?
谢谢!
答案 0 :(得分:1)
似乎正在使用的Typescript编译器是2.4之前的版本,它们在枚举中添加了字符串值支持。通常,从值到枚举存在反向映射,并且值通常是数字。但是,如果您尝试使用2.4之前的字符串,则编译器将不知道如何处理(实际上会产生错误),但仍会生成源代码。
比较2.4:
var Sizes;
(function (Sizes) {
Sizes["Tiny"] = "Tiny";
Sizes["VerySmall"] = "Very Small";
Sizes["Small"] = "Small";
Sizes["Medium"] = "Medium";
Sizes["Large"] = "Large";
Sizes["VeryLarge"] = "Very Large";
})(Sizes || (Sizes = {}));
至2.3:
var Sizes;
(function (Sizes) {
Sizes[Sizes["Tiny"] = "Tiny"] = "Tiny";
Sizes[Sizes["VerySmall"] = "Very Small"] = "VerySmall";
Sizes[Sizes["Small"] = "Small"] = "Small";
Sizes[Sizes["Medium"] = "Medium"] = "Medium";
Sizes[Sizes["Large"] = "Large"] = "Large";
Sizes[Sizes["VeryLarge"] = "Very Large"] = "VeryLarge";
})(Sizes || (Sizes = {}));
2.3没有字符串值:
var Sizes;
(function (Sizes) {
Sizes[Sizes["Tiny"] = 0] = "Tiny";
Sizes[Sizes["VerySmall"] = 1] = "VerySmall";
Sizes[Sizes["Small"] = 2] = "Small";
Sizes[Sizes["Medium"] = 3] = "Medium";
Sizes[Sizes["Large"] = 4] = "Large";
Sizes[Sizes["VeryLarge"] = 5] = "VeryLarge";
})(Sizes || (Sizes = {}));
如果要在2.4及更高版本中强制执行反向映射,可以将值声明为any
。
enum Sizes {
Tiny = <any>"Tiny",
VerySmall = <any>"Very Small",
Small = <any>"Small",
Medium = <any>"Medium",
Large = <any>"Large",
VeryLarge = <any>"Very Large"
}
只需将其称为功能即可。
答案 1 :(得分:0)
在TypeScrit中
enum Sizes {
Tiny = "Tiny",
VerySmall = "Very Small",
Small = "Small",
Medium = "Medium",
Large = "Large",
VeryLarge = "Very Large"
}
class Test {
constructor() {
let text = '';
for (const key in Sizes) {
if (Sizes.hasOwnProperty(key)) {
text += Sizes[key] + '<br/>';
}
}
console.log(text);
text = '';
Object.keys(Sizes).map(key => text += Sizes[key] + '<br/>');
console.log(text);
}
}
let t = new Test();
请记住,for-In应该具有if-Statement!
console.log(text)
都应输出相同的字符串。
Tiny<br/>Very Small<br/>Small<br/>Medium<br/>Large<br/>Very Large<br/>
答案 2 :(得分:0)
您可以使用Object.keys
获取枚举键并记录值,如下所示:
enum Sizes {
Tiny = "Tiny",
VerySmall = "Very Small",
Small = "Small",
Medium = "Medium",
Large = "Large",
VeryLarge = "Very Large"
}
for (const size of Object.keys(Sizes)) {
console.log(Sizes[size]);
}
输出:
Tiny
Very Small
Small
Medium
Large
Very Large
已翻译的示例:
var Sizes;
(function (Sizes) {
Sizes["Tiny"] = "Tiny";
Sizes["VerySmall"] = "Very Small";
Sizes["Small"] = "Small";
Sizes["Medium"] = "Medium";
Sizes["Large"] = "Large";
Sizes["VeryLarge"] = "Very Large";
})(Sizes || (Sizes = {}));
for (var _i = 0, _a = Object.keys(Sizes); _i < _a.length; _i++) {
var size = _a[_i];
console.log(Sizes[size]);
}