Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get index by value in javascript array

Reading the 'enum' in typescript, I see this code compiled to 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 Season to {} empty objext at first line, this also works and it makes sense. I don't know what's happening hear. What is this?

Edit: Yes. This is not what compiler generate. Compiler uses empty object. But if I changed it to empty array. It still works. My question was why array also works good. At first my question included both version, but someone edited question and delete object-use version.

like image 885
monad98 Avatar asked Dec 24 '22 09:12

monad98


2 Answers

This:

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

Creates eight properties in Season object:

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

After that Season can be requested:

  1. by text to get its index (first four properties)
  2. by index to get its text (second four properties)
like image 81
c-smile Avatar answered Dec 27 '22 00:12

c-smile


Looks like someone is just trying to make Season be a bidirectional map.

In other words, you can look up items by numeric index or by their string value.

var season1     = Season[1];        // season1 == 'Summer'
var summerIndex = Season['Summer']; // summerIndex == 1
like image 26
GreenGiant Avatar answered Dec 26 '22 23:12

GreenGiant