TypeScript - weird behaviour when iterating over an enum

问题: 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.

  • 发表于 2019-01-09 19:05
  • 阅读 ( 252 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除