当我有专门针对它的 IF 语句时,为什么我的输出不包括空格?

Why is my output not including spaces when I have an IF statement specifically for it?

我正在尝试制作凯撒密码以应对挑战,我必须遵守特定规则:

JS代码:

function shift8(string){
  string = string.toUpperCase();
  const alphabetArray = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
  let shiftedString = '';
  
  for (i = 0; i < string.length; i++) {
    var currentIndex = alphabetArray.indexOf(string[i]);
    var newIndex = currentIndex + 8;
    var currentCharacter = alphabetArray[currentIndex];
    var shiftedCharacter = alphabetArray[newIndex];
    if (currentCharacter == ' ') {
      shiftedString += ' ';
    } else if ('ABCDEFGHIJKLMNOPQRSTUVWXYZ '.includes(shiftedCharacter)) {
      shiftedString += shiftedCharacter;
    }
  }
  return shiftedString;
}
var output = shift8('The quick brown fox jumps over the lazy dog');
console.log(output);

有什么我想念的吗?我的逻辑不对吗?

alphabetArray.indexOf(string[i]) 将为不属于 alphabetArray 的所有值 return -1,例如空格。这意味着 currentCharacter 对于任何此类值都是未定义的。

要解决此问题,请执行 var currentCharacter = string[i];

您的变量 currentCharacter 只是 alphabetArray 的一个成员,它不包含任何 ' '(空格),这就是它从未被触发的原因。

在这里,我重构了你的代码。有一件重要的事情 - 你需要循环这些索引,因为它们的最大值应该是 alphabetArray.length.

function shift8(string){
  string = string.toUpperCase();
  const alphabetArray = 'ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVWXYZA'.split('');
  let shiftedString = '';
  
  for (i = 0; i < string.length; i++) {

    let oldCharacter = string[i];
    if( !alphabetArray.includes(oldCharacter) ){

       if( oldCharacter == ' ' ) shiftedString += oldCharacter;

    } else{

       let currentIndex = alphabetArray.indexOf(oldCharacter);
       let newIndex     = (currentIndex + 8) % alphabetArray.length;
       let shiftedCharacter = alphabetArray[newIndex];
       shiftedString += shiftedCharacter;

    }
  }
  return shiftedString;
}
var output = shift8('The quick brown fox jumps over the lazy dog');
console.log(output);

对于 space 以下将 return -1

var currentIndex = alphabetArray.indexOf(string[i]); 

如果你应该在你的代码中使用 8 的移位,alphabetArray 不需要在字母表中的前八个字符之后有重复的值,因为你永远不会使用这些值。

代码应该是:

    function shift8(string){
    string = string.toUpperCase();
    const alphabetArray = 'ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGH'.split('');
    let shiftedString = '';
    
    for (i = 0; i < string.length; i++) {
        const element = string[i]
        if (element == ' ') {
             shiftedString += ' ';
        } else {
            const currentIndex = alphabetArray.indexOf(string[i]);
            if(currentIndex === -1){ // To not include  symbols such as #*!$^
                continue
            }
            const newIndex = currentIndex + 8;
            const currentCharacter = alphabetArray[currentIndex];
            const shiftedCharacter = alphabetArray[newIndex];
            shiftedString += shiftedCharacter
        }  
    }
    return shiftedString;
}
var output = shift8('The quick brown fox jumps over the lazy dog');
console.log(output); // CPM ZDQKS JAXHV NXF RDUYB XEMA CPM TIHG LXO