比较运算符不工作(Java脚本)

时间:2018-04-06 03:49:29

标签: javascript algorithm comparison-operators

我正在尝试用字母表中的下一个字母替换字符串的所有字母。

例如:a - > b或i - >学家

我的程序忽略了检查字母数组字母的if语句。当我尝试运行代码时,它将所有字母替换为“A”,即字母数组中的最后一个元素。

虽然效果不好,但我发现这个算法没有任何错误。那么为什么程序会忽略if语句?

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","a"];
str = str.toLowerCase();
var ans = str.split("");

for(i = 0; i < ans.length; i ++)//Running through for each letter of the input string
{
    for(a = 0; a < 26; a++)//Checking each letter against the alphabet array
    {
        if(alphabet[a] == ans[i])
        {
          ans[i] = alphabet[a+1];
        }
    }
}
return ans;
}

LetterChanges("Argument goes here");

2 个答案:

答案 0 :(得分:2)

它无法正常工作的原因是因为ans数组已被修改,而您仍在检查它。

在这个循环中:

for(a = 0; a < 26; a++)//Checking each letter against the alphabet array
{
    if(alphabet[a] == ans[i])
    {
      ans[i] = alphabet[a+1];
    }
}

如果发现if语句为真,则ans[i]将被更新,但是在迭代的下一个循环中,它可能会再次出现,因为您正在检查更新ans[i]变量。

正如@ xianshenglu建议的那样,一旦找到正确的匹配,你可以通过添加break来解决这个问题。

for(a = 0; a < 26; a++) {
  if(alphabet[a] == ans[i]) {
    ans[i] = alphabet[a+1]
    // escape from the inner loop once a match has been found
    break
  }
}

有关替代方法,您可以执行以下操作:

var result = str.toLowerCase().split('').map(ch => {
  var pos = alphabet.indexOf(ch)
  return pos >= 0 ? alphabet[pos + 1] : ch
}).join('')

如果你想摆脱alphabet数组,你可以使用char代码。例如:

var result = str.toLowerCase().split('').map(ch => {
  var code = ch.charCodeAt(0)
  if(code < 96 || code > 122){ return ch }
  return String.fromCharCode((code - 96) % 26 + 97)
}).join('')

答案 1 :(得分:0)

break执行时遗失了if

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","a"];
str = str.toLowerCase();
var ans = str.split("");

for(i = 0; i < ans.length; i ++)//Running through for each letter of the input string
{
    for(a = 0; a < 26; a++)//Checking each letter against the alphabet array
    {
        if(alphabet[a] == ans[i])
        {
          ans[i] = alphabet[a+1];
           break;
        }
    }
}
return ans;
}

console.log(LetterChanges("Argument goes here"));