官术网_书友最值得收藏!

Using enum

enum allows us to group values with more intuitive names. Some people prefer to call the enumerated list and some other names. Let's look at an example, so as to make it easier to understand how this works in practice:

  1. Create a file called enum.js in the chapter-02 folder, and add the following code:
enum bands {
Motorhead,
Metallica,
Slayer
}
console.log(bands);
  1. In your Terminal, type the following command to transpile the file:
tsc enum.ts
  1. Now, let's execute the file. Type the following command:
node enum.js

You will see the following result in the Terminal:

{ '0': 'Motorhead',
'1': 'Metallica',
'2': 'Slayer',
Motorhead: 0,
Metallica: 1,
Slayer: 2 }

We can now get the value by using the name instead of the position.

  1. Add the following lines of code, right after the console.log() function:
let myFavoriteBand = bands.Slayer;
console.log(myFavoriteBand);

Now, execute the commands in steps 2 and step 3 to check the results. You will see the following output in the Terminal:

{ '0': 'Motorhead',
'1': 'Metallica',
'2': 'Slayer',
Motorhead: 0,
Metallica: 1,
Slayer: 2 }
My Favorite band is: Slayer

Note that all of the values (band names) declared in the band object are converted into strings, inside an indexed object, as you can see in the preceding example.

主站蜘蛛池模板: 榆社县| 永城市| 榆林市| 靖边县| 吉隆县| 德化县| 湘潭县| 牡丹江市| 天台县| 五河县| 昭通市| 山阴县| 曲麻莱县| 隆回县| 吉林市| 富平县| 镇雄县| 偃师市| 五河县| 牡丹江市| 崇信县| 城市| 双峰县| 博爱县| 浠水县| 海伦市| 成安县| 冀州市| 维西| 师宗县| 安陆市| 沛县| 通州区| 兴义市| 富裕县| 阿克| 桓台县| 化隆| 汉川市| 博白县| 法库县|