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

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.

主站蜘蛛池模板: 洛阳市| 临清市| 金昌市| 汕尾市| 平安县| 淳化县| 林西县| 临沂市| 平江县| 新建县| 图们市| 襄汾县| 紫云| 确山县| 阿拉善盟| 白河县| 济南市| 淳化县| 登封市| 武乡县| 江华| 双桥区| 建平县| 高要市| 阿鲁科尔沁旗| 罗城| 辽宁省| 祁东县| 镇原县| 黄陵县| 佛学| 福安市| 青岛市| 乐亭县| 万荣县| 新巴尔虎左旗| 望江县| 邵武市| 虹口区| 沭阳县| 吴江市|