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