What is the fastest way to assign array based variables?

What is the fastest way, in terms of readability / input, to assign a value to a specific variable based on a related variable?

var abbrev; if(state=='Pennsylvania'){ abbrev='PA'; }else if(state=='New Jersey'){ abbrev='NJ'; }else if(state=='Delaware'){ abbrev='DE'; } //and so on... 

I am trying to avoid creating one array for the state name and another array for the abbreviation because the connection is lost with individual declarations.

+5
source share
3 answers

You can use object for abbreviation, for example

 var abbreviations = { 'Pennsylvania': 'PA', 'New Jersey': 'NJ', 'Delaware': 'DE' }; 

Using:

 abbrev = abbreviations[state]; 
+7
source

just a suggestion, have you tried using CASE? it looks cleaner and more readable

+1
source

try:

 var abbrev = ''; if(state.indexOf(' ') == -1){ abbrev = state.substring(0,2).toUpperCase(); }else{ var firstLetter = state.substring(0,1).toUpperCase(); var secoundLetter = state.substring(state.indexOf(' '),1).toUpperCase(); abbrev = firstLetter + secoundLetter; } alert(abbrev); 
0
source

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


All Articles