所以我一直在制作这个密码,而且如果我输入' a'如果换班次为1则输出' b'这是对的,但如果我放入' ab'或任何其他长度的字符串,它' bl'例如。我该如何解决这个问题?
function encryption(str, amount) {
var str = document.getElementById('inputText').value;
var amount = document.getElementById('amountDropdown').value;
var result = "";
//loop through each character in word
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
//If the character is uppercase
if ((c >= 65) && (c <= 90)) {
result += String.fromCharCode(((c - 65 + amount) % 26) + 65);
}
//if the character is lowercase
else if ((c >= 97) && (c <= 122)) {
result += String.fromCharCode(((c - 97 + amount) % 26) + 97);
}
//if the character isn't a letter
else {
result += str.charAt(i);
}
}
//return the result
outputResult.innerHTML = "The text you have input has been encrypted to.." + result;
}
function decryption() {
var str = document.getElementById('inputText').value;
var amount = document.getElementById('amountDropdown').value;
var result = "";
//loop through each character in word
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
//If the character is uppercase
if (c >= 65 && c <= 90) {
result += String.fromCharCode((c - 65 - amount) % 26 + 65);
}
//if the character is lowercase
else if (c >= 97 && c <= 122) {
result += String.fromCharCode((c - 97 - amount) % 26 + 97);
}
//if the character isn't a letter
else {
result += str.charAt(i);
}
}
//return the result
outputResult.innerHTML = "The text you have input has been encrypted to.." + result;
}
function encryptClickHandler() {
document.getElementById('inputText').value = encrypt(document.getElementById('inputText').value, document.getElementById('amount').value);
}
function decryptClickHandler() {
document.getElementById('inputText').value = decrypt(document.getElementById('inputText').value, document.getElementById('amount').value);
}
答案 0 :(得分:1)
输入字段的值始终为字符串。
计算(c - 97 - amount) % 26
时,会得到以下结果:
c = 97, amount = 1 => (97 - 97 + 1) % 26 = (0 + 1) % 26 = 1 % 26 = 1
c = 98, amount = 1 => (98 - 97 + 1) % 26 = (1 + 1) % 26 = 2 % 26 = 2
c = 97, amount = '1' => (97 - 97 + '1') % 26 = (0 + '1') % 26 = '01' % 26 = 1
c = 98, amount = '1' => (98 - 97 + '1') % 26 = (1 + '1') % 26 = '11' % 26 = 11
要解决此问题,请将值转换为整数:
var amount = parseInt(document.getElementById('amountDropdown').value, 10);