简体   繁体   中英

JavaScript: Condensing if else statement

Is there a shorter more efficient way of doing this? it seems a little hefty and I just want to know if it can be condensed?

 var y = []

  for(let i=0;i < word.length;++i){
    if(word[i] == "A"|| word[i] == "a"){
      y.push(0)
    }
    else if(word[i] == "B"|| word[i] == "b"){
      y.push(1);
    }
    else if(word[i] == "C"|| word[i] == "c"){
      y.push(2);
    }
    else if(word[i] == "D"|| word[i] == "d"){
      y.push(3);
    }
and so on..


  return(y);
}

One option is to use an array of characters, then use .indexOf to find the index of the character:

 const word = 'bBac'; const chars = ['a', 'b', 'c', 'd']; const y = [...word].map(char => chars.indexOf(char.toLowerCase())) console.log(y); // return y; 

For slightly better efficiency, instead of .indexOf (which is O(N) ), use a Map ( O(1) ):

 const word = 'bBac'; const charMap = new Map([ ['a', 0], ['b', 1], ['c', 2], ['d', 3] ]); const y = [...word].map(char => charMap.get(char.toLowerCase())) console.log(y); // return y; 

You can make use of the ASCII values, which eliminates the need to maintain a structure containing all the letters:

let letterValue = word[i].toUpperCase().charCodeAt(0) - 65;  // 65 represents the offset of the alphabet in the ASCII table
if (letterValue >= 0 && letterValue <= 25) {  // Check that the value is A-Z
  y.push(letterValue);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM