循环似乎永远不会中断/系统过载



在学校,我们必须编写一个函数,通过将消息中的每个字母移动字母表中的"nC"(或niveuCryptage(数字来加密特定消息。

目前,每当我执行代码时,在完成两个用户交互(即询问字母在字母表中移动的数字以及用户想要加密的消息(后,我都会被困在一个永远加载的屏幕上。我怀疑环路出了问题。

function crypter(t, l, nC) {
//This function receives the alphavet Table, a letter, and the number by which the letter has to be shifted in the alphabet.
//This function returns a single crypted letter...
var crypte = '';
var i = 0;
while (t[i] != l) {
i++;
}
if (i + nC > t.length) {
crypte = (i + nC) - (t.length);
} else {
crypte = i + nC;
}
return crypte;
}
//Global variables
var tAlphaB = ['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', ' '
];
var niveauCryptage = 0;
var texteBase = '';
var tTexteAvant = new Array();
var tTexteApres = [];
var txt = 'Le résultat du cryptage est : nn';
//Main program
//Ask the user to specify the number by which the letters of the message have to be shifted in the alphabet
//This number has to be a number between 1 and 10 (1 and 10 included)
do {
niveauCryptage = parseFloat(prompt("Saisissez un nombre entre 1 et 10 pour selectionner le niveau de cryptage"));
} while (isNaN(niveauCryptage) || niveauCryptage > 10 || niveauCryptage < 1)

//Ask the user to enter a message on the condition that it is a chain of characters
do {
texteBase = prompt("Quel texte voudrez-vous crypter?");
} while (!isNaN(texteBase))
//Transform the message into the table tTexteAvant using the split('') function
tTexteAvant = new Array(texteBase.split(''));
//Encrypt each letter of the table, tTexteAvant, into a new table, tTexteApres          
var j = 0;
while (j < tTexteAvant.length) {
tTexteApres.push(crypter(tAlphaB, tTexteAvant[j], niveauCryptage));
j++;
}

tTexteAvant = new Array(texteBase.split(''));将创建一个包含单个项的数组,该项将是包含字符的数组。

您很可能想要tTexteAvant = texteBase.split('');

正如Jesse的评论中所述,当字符l不在数组中时,即当它是小写或标点符号时,crypter函数中的这一部分将进行无限循环。

while (t[i] != l) {
i++;
}

如果你只需要查找字符串的元素是否存在于数组中,你可以用一个数组函数来替换该部分,该函数可以查找值并返回数组中的索引(如果没有找到,则为-1(:

i = t.indexOf(l);

然后,您应该决定如何处理无效或无法识别的字符,或者提示用户输入有效的字符串(只有大写字母字符和空格(。如果可以接受的话,您也可以决定将任何小写字符转换为大写字符。

附带说明一下,请检查crypter函数的返回值:它返回的是新索引,而不是新字母。正如函数开头所评论的,这不是预期的行为。

最新更新