Get index by value in javascript array

Reading "enum" in typescript, I see that this code is compiled in javascript.

var Season = [];
Season[Season["Spring"] = 0] = "Spring";
Season[Season["Summer"] = 1] = "Summer";
Season[Season["Fall"] = 2] = "Fall";
Season[Season["Winter"] = 3] = "Winter";

console.log(Season.Spring); // 0
console.log(Season[0]); // Spring

and if I change the season to {} an empty objext in the first line, this also works, and that makes sense. I do not know what's happening. What is it?

Edit: Yes. This is not what the compiler generates. The compiler uses an empty object. But if I changed it to an empty array. It still works. My question was why the array also works well. At first, my question included both versions, but someone edited the question and deleted the version of using the object.

+4
source share
4 answers

It:

Season[Season["Spring"] = 0] = "Spring";
Season[Season["Summer"] = 1] = "Summer";
Season[Season["Fall"] = 2] = "Fall";
Season[Season["Winter"] = 3] = "Winter";`

Season:

Season["Spring"] = 0;
Season["Summer"] = 1;
Season["Fall"] = 2;
Season["Winter"] = 3;
Season[0] = "Spring";
Season[1] = "Summer";
Season[2] = "Fall";
Season[3] = "Winter";

:

  • , ( )
  • , ( )
+5

, - .

, .

var season1     = Season[1];        // season1 == 'Summer'
var summerIndex = Season['Summer']; // summerIndex == 1
+3

Season {} objext , ,

, : :

Season = [];

Season = {};

TypeScript:

enum Season {
    Spring,
    Summer,
    Fall,
    Winter
}

JavaScript:

var Season;
(function (Season) {
    Season[Season["Spring"] = 0] = "Spring";
    Season[Season["Summer"] = 1] = "Summer";
    Season[Season["Fall"] = 2] = "Fall";
    Season[Season["Winter"] = 3] = "Winter";
})(Season || (Season = {}));

Season = {}. .

PS:

, , Season[Season["Spring"] = 0] = "Spring"; .

0

, - , var Season = [];, Season . , , JavaScript, ( Object.freeze). , Season["Spring"] = 0 "Spring" Season, , Season["Spring"] Season.Spring , .

0

Source: https://habr.com/ru/post/1626461/


All Articles