Je fais le défi algorithmique freecodecamp "Caesars Cipher". J'ai un problème avec mon code. J'essaie de générer une table de recherche en tant qu'objet dynamique et pour une raison quelconque, il ne s'enregistre pas. Lorsque vous faites console.log, il est dit "table de recherche est indéfini". C'est la même chose avec la variable Acode. Si je commente le fichier console.logs alors cela fonctionnera mais il ne cryptera rien à cause de la partie ci-dessous qui vérifie si le caractère de strArr existe dans le lookupTable, sinon il devrait assigner la même valeur à encryptedArr (c'était fait de ne pas chiffrer des virgules, espaces, etc.):JavaScript Dynamiquement créé objet indéfini
strArr.forEach(function(thisArg) {
var newValue;
if(lookupTable[thisArg] !== undefined) {
newValue = lookupTable[thisArg];
} else {
newValue = thisArg;
}
encryptedArr.push(newValue);
});
Ofcourse LookupTable [thisArg] est toujours définie. Voici toute la fonction de la partie ci-dessus ainsi:
function rot13(str) { // LBH QVQ VG!
var strArr;
var encryptedArr = [];
var Acode;
var lookupTable = {}; //this object will contain the mapping of letters
var encryptedString;
//check the code of A , this will be a reference for the first letter as the algorith will use Modular Arithmetic
Acode = 'A'.charCodeAt(0);
console.log(Acode);
//generate an object containing mappings (I din't want to do it initially but theoreticaly just making lookups in a table would be more efficiant for huge workloads than calculating it every time)
//this algorithm is a little bit complecated but i don't know how to do modular arithmetic in code properly so I use workarrounds. If a = 101 then I do 101 + the remainder from current letter((Acode + 1) - 13) divided by 26 which works
for (i = 0; i < 26; i++) {
lookupTable[String.fromCharCode(Acode + i)] = String.fromCharCode(Acode + ((Acode + i) - 13) % 26);
console.log(lookupTable[String.fromCharCode(Acode + i)]);
}
//save the string into the array
strArr = str.split("");
//change letters into numbers and save into the code array
strArr.forEach(function(thisArg) {
var newValue;
if (lookupTable[thisArg] !== undefined) {
newValue = lookupTable[thisArg];
} else {
newValue = thisArg;
}
encryptedArr.push(newValue);
});
encryptedString = encryptedArr.join("");
return encryptedString;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
console.log(Acode);
ce que je fais mal à la création d'objets LookupTable et avec le bas?
Acode = 'A'.charCodeAt(0);
'Acode + ((Acode + i) -13)% 26' est faux. Il devrait être 'Acode + ((i + 13)% 26)' – Barmar
Avez-vous essayé 'console.log (lookupTable)'? – Barmar
Pouvez-vous essayer de faire 'console.log (strArr)'? Il semble que le contenu de ce tableau pourrait être différent de ce qui était attendu. – DBWhite