有没有一种更简洁的方法来设置一个条件语句,以便为变量的任意值集执行

Is there a more concise way to set up a conditional statement to execute for an arbitrary set of values of a variable?

本文关键字:语句 任意值 执行 条件 变量 设置 一种 简洁 方法 有没有 一个      更新时间:2023-09-26

有没有一种更有效/简洁/雄辩的方法来写这个:

else if ((aInd === 3)||(aInd === 7)||(aInd === 9)||(aInd === 19)
     letter = alphabet[aInd + 1].toUpperCase();

是否有类似的有效语法

if (a === (3 || 7 || 13 || 19) {do this}

或者让您用一种比一堆带有||logic的布尔表达式更简洁的方式对单个变量的值集进行分组?

背景:新手程序员,正在对coderbyte进行基本的密码挑战,如果字母是元音,则需要采取特定的操作(大写)。为了简单起见(因为它在程序的其他地方使用),我声明了一个数组字母表,其中包含字符串形式的每个字母a-z。"cypher"还将每个字母向右转置一个,因此成为元音的字母的字母索引为3、7、13和19。and表示字母表中字母的索引。

完整代码:

function letterChanges(str) {
    var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
    var words = str.toLowerCase().split(' '), senArray = words.map(function(word) {return word.split('')});
    senArray.forEach(function(word) {
        word = word.filter(function(letter, index, word) {
            if ((Boolean(alphabet.indexOf(letter))) === false) return false;
            else return true;
        });
    });
    senArray[0].map(function(letter) {
        var aInd = alphabet.indexOf(letter);
        switch (aInd) {
            case 25: 
                letter = alphabet[aInd].toUpperCase();
                break;
            case (3 || 7 || 13 || 19):
                letter  = alphabet[aInd + 1].toUpperCase();
                console.log(letter);
                break;
            default:
                letter  = alphabet[aInd + 1];
                break;
        }
        return letter;
    })
    
    return senArray.map(function(word) {
        return word.map(function(letter) {
        var aInd = alphabet.indexOf(letter);
        if (aInd === 25) {letter = alphabet[aInd].toUpperCase();}
        else if ((aInd === 3)||(aInd === 7)||(aInd === 13)||(aInd === 19)) {letter  = alphabet[aInd + 1].toUpperCase();}
        else {letter  = alphabet[aInd + 1];}
        return letter;
    }).join('');
    }).join(' ');
}
letterChanges("Input string goes here.");

将值作为数组传递并检查indexOf

在您的情况下,

if ([3, 7, 13, 19].indexOf(aInd) > -1) {
  letter  = alphabet[aInd + 1].toUpperCase();
}