Skip to main content
 首页 » 编程设计

JavaScript:压缩 if else 语句

2024年12月31日13arxive

有没有更短更有效的方法?好像有点重,我就想知道能不能压缩?

 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); 
} 

请您参考如下方法:

一个选择是使用一个字符数组,然后使用.indexOf 来查找字符的索引:

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

为了稍微提高效率,使用 Map(O(O(N))代替 .indexOf (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;