JavaScript 数组中的标点符号返回“undefined”

3

我正在尝试编写一个小的密码程序,需要将单词和标点符号组合起来。如果我使用字母/数字/特殊字符!到),代码可以完美运行,但是使用逗号、句号或问号时就无法正常工作。我检查了代码,发现仅在这三个标点符号下返回未定义。我之前编写过一个剥离所有标点符号的代码版本,它可以正常工作,现在我正在尝试再次加入标点符号。

var alpha = ["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", "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", " ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", ",", ".", "?"];


else if (oldLet == "!") {
    index = 63;
    keyIndex = keyIndex - 1;
} else if (oldLet == ".") {
    index = 84;
    keyIndex = keyIndex - 1;
} else if (oldLet == "?") {
    index = 85;
    keyIndex = keyIndex - 1;
}

var newLet = alpha[index];
alert(newLet);
cipherArray.push(newLet);
}
cipherArray = cipherArray.join("");
document.getElementById("output").innerHTML = cipherArray;
}

对于字母、数字和特殊字符,代码可以完美地运行,但无法正确处理标点符号,这让我感到非常困惑。欢迎提供任何帮助。


为什么不创建一个查找映射表来设置索引,而不是手动设置呢? const indexByChar = new Map(alpha.map((char, index) => [char, index])) 然后你可以这样做:index = indexByChar.get(oldLet) - 3limin4t0r
1个回答

3

我觉得你使用了错误的索引。

   else if(oldLet == ","){
                alert("got here 2" + oldLet);
                index = 83;
                alert("got here 3" + alpha[index]);
                keyIndex = keyIndex -1;
            }
            else if(oldLet == "."){
                index = 84;
                keyIndex = keyIndex -1;
            }
            else if(oldLet == "?"){
                index = 85;
                keyIndex = keyIndex -1;
            }
            

看,不是83、84、85,而是73、74和75。

你可以这样检查:

alert(alpha.indexOf(","));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接