简体   繁体   中英

affecting values into arrays isn't working in JavaScript?

I'm trying to make Ceaser cipher that shifts the input by the value you chose, for example you chose 3, and the program will shift letters by 3 to the back, so i created an array type variable alpha that contains letters from a to z, and create two other variable one is the shift value and the other is a string filled by the user, my idea was to compare each letter from the input with alpha and if they match then i will replace it with the shifted value.

input[i] = alpha[j-shift_value];

i wanted to do it as simple as possible but for some reason it's not working, I'll provide a code snippet.

 var ClearText = document.getElementById("txt_clr").value; var DecValue = document.getElementById("valeur_dec").value; var alpha = "abcdefghijklmnopqrstuvwxyz"; var longeur = ClearText.length; // alpha[0]=a; // alpha[26]=z; var i; function decalager() { for (i = 0; i < longeur; i++) { for (let j = 0; j < 26; j++) { if (ClearText[i] == alpha[j]) { ClearText[i] = alpha[j - DecValue]; } } } console.log(ClearText); document.getElementById("resultat").innerHTML = ClearText; }
 body { height: 100vh; width: 100vw; justify-content: center; align-items: center; margin: 0; background-color: #002b36; display: flex; }.centrer { margin: auto; } p { color: wheat; font-size: 18px; font-style: italic; } textarea { border: 1px black solid; border-radius: 15px; padding: 5px; } button, input { height: 50px; width: 113px; border: 0; border-radius: 15px; }
 <html> <head> <meta charset="utf-8"> <title>test</title> </head> <body> <div class="centrer"> <p>Décalage: </p> <input id="valeur_dec" type="text"> <button onclick="decalager()">Chiffrer</button> <p>Texte claire: </p> <textarea id="txt_clr" cols="30" rows="10"></textarea> <p>Texte avec Décalage: </p> <textarea id="resultat" cols="30" rows="10"></textarea> </div> </body> </html>

Strings are immutable in JavaScript.

const greeting = "Hello"
console.log(greeting[0]) // H
greeting[0] = "A"
console.log(greeting[0]) // H

You can turn your string into an array, modify it and then turn it back into a string again.

const greeting = "Hello"
const greetingArray = [...greeting]
console.log(greetingArray) // ["H", "e", "l", "l", "o"]
const alpha = "abcdefghijklmnopqrstuvwxyz"
const shift = 3
for(const [charIndex, char] of Object.entries(greetingArray)) {
    const alphaIndex = alpha.indexOf(char.toLowerCase())
    greetingArray[charIndex] = alpha[(alphaIndex + shift) % alpha.length] 
}
const shiftedGreeting = greetingArray.join("")
console.log(shiftedGreeting) // khoor

Strings are immutable, so you will need a function to replace a letter at each index. It's easiest to define this as a method on the String prototype Object.
Then the action function will need an input parameter, in this case you would want to input ClearText and DecValue to shift the string by, and this will call the replaceAt() method.

var ClearText = document.getElementById("txt_clr").value;
var DecValue = document.getElementById("valeur_dec").value;
var alpha = "abcdefghijklmnopqrstuvwxyz";
var longeur = ClearText.length;

// alpha[0]=a;
// alpha[25]=z;

String.prototype.replaceAt = function(index, replacement) {
    return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}

function decalager(clearText, decValue) {

  for (let i = 0; i < longeur; i++) {
    for (let j = 0; j < 26; j++) {
      if (clearText[i] == alpha[j]) {
        clearText = clearText.replaceAt(i, alpha[j-decValue])
      }
    }
  }

  console.log(clearText);
  document.getElementById("resultat").innerHTML = clearText;
}

Then call this with decalager(ClearText, DecValue);.
Read more about the replaceAt() method here: How do I replace a character at a particular index in JavaScript?

You just need to simply .split('') both strings (input and alphabet) then compare array to array. then. join('') the final result (array to string).

But make sure to include (j - devValue) > 0 in your condition because you don't want to go negative on index. Or you can just simply do alpha[0] if j - decValue is negative.

 var stringOne = "apppele" var stringTwo = "abcdefghijklmnopqrstuvwxyz" var decValue = 2; var stringOneArray = stringOne.split(''); var stringTwoArray = stringTwo.split(''); for (i = 0; i < stringOneArray.length; i++){ for (j = 0; j < stringTwoArray.length; j++) { if (stringOneArray[i] == stringTwoArray[j] && (j - decValue > 0)) { console.log("index #" + i + " (" + stringOneArray[i] + ") changed to " + stringTwoArray[j - decValue]); stringOneArray[i] = stringTwoArray[j - decValue] } } } var stringOneJoined = stringOneArray.join(''); console.log("Final result: " + stringOneJoined);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM