【问题标题】:Is there a more concise way to set up a conditional statement to execute for an arbitrary set of values of a variable? [duplicate]是否有更简洁的方法来设置条件语句以执行任意一组变量值? [复制]
【发布时间】:2015-11-25 18:19:59
【问题描述】:

有没有更高效/简洁/雄辩的方式来写这个:

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

是否有任何看起来像的有效语法

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

... 或者让您以比使用 || 的布尔表达式更简洁的方式对单个变量的值集进行分组。逻辑?

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

完整代码:

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.");

【问题讨论】:

  • 刚刚注意到我错过了顶部示例中的 ) 。它应该是:if (a === (3 || 7 || 13 || 19)) {做这个}。哎呀。

标签: javascript


【解决方案1】:

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

在你的情况下,

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

【讨论】:

  • 我试图用一个 switch 语句来做到这一点,这将需要多个案例并执行相同的事情,但我认为这是不可能的,因为我正在这样做。这是一个很好的替代方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
  • 2012-11-10
  • 1970-01-01
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
  • 2015-11-08
相关资源
最近更新 更多