问题:
I noticed this just now when trying to iterate over an enum.
Say you have:
enum Gender {
Male = 1,
Female = 2
}
and you do:
for (let gender in Gender) {...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I noticed this just now when trying to iterate over an enum.
Say you have:
enum Gender {
Male = 1,
Female = 2
}
and you do:
for (let gender in Gender) {
console.log(gender)
}
This will run 4 (?) times. First printing string (!) representations of 1 and 2, then printing the strings Male and Female.
I can only suppose this is intended. My question is why this is the case? What's the reasoning behind this (in my opinion) weird implementation?
回答1:
JS has no enum. TS compiles your enum to:
var Gender;
(function (Gender) {
Gender[Gender["Male"] = 1] = "Male";
Gender[Gender["Female"] = 2] = "Female";
})(Gender || (Gender = {}));
Where you can see has 4 keys (1,2,Male,Female).
You can use this site for checking the TS to JS compilation output.