【问题标题】:JavaScript: Condensing if else statementJavaScript:压缩 if else 语句
【发布时间】:2019-05-06 13:25:49
【问题描述】:

有没有更短更有效的方法来做到这一点?好像有点重,我就是想知道能不能浓缩?

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

【问题讨论】:

  • 您可能会发现在索引时使用字符而不是字符串很有用。这样,您可以使用以下内容将整个 if/else 压缩为几行:*.com/questions/94037/…
  • 嗨;你的问题得到回答了吗?您尚未标记已接受的答案,因此如果您还有其他需要,请告诉我们。

标签: javascript if-statement


【解决方案1】:

一种选择是使用字符数组,然后使用.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(1)),而不是.indexOf(即O(N)):

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;

【讨论】:

    【解决方案2】:

    您可以使用 ASCII 值,这样就无需维护包含所有字母的结构:

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

    【讨论】: