mercredi 19 juin 2019

indexOf and for loop not working properly, please help me understand why

My goal is to advance each letter by three, for example, 'a' becomes 'd' and 'z' becomes 'c' etc. and ignore characters which are not letters. I wrote a similar program in Python that works perfect, but I am having trouble understanding the for loop and the if/else if/else statements that follow regarding my variable char. I also do not understand why I am getting lc.indexOf(char) = -1...as though its not even in my array.

Here is a sort of timeline regarding what I have tried:

I converted the strings to arrays because JS would not accept a string in a for loop, as in char in str...it would tell me it needed to be an object so I used the .split() function.

I checked that my arrays were correct with window propmts

I changed the variable 'increase' to 2 and 4 and got 3 b's and d's respectively

I checked the indexOf(char) within the if statements and they return -1

It does not appear that variable char ever gets past the initial if statement...even if var str = ZZ2, I will still get all lowercase answers.

I have been programming for only 3 weeks, so please be help me to understand not only how to do this in javascript, but why its not working and why the correct method DOES work properly.

<p id="response"></p>
//I want to advance these characters by 3, ignoring the !
<script>
var str = "2Za";
var lowercase = "abcdefghijklmnopqrstuvwxyz";
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var increase = 3;
var answer = "";
var strarr = str.split("");
var lc = lowercase.split("");
var uc = uppercase.split("");
var char;
for (char in strarr) {
    if (char in lc) {
      answer += lc[(lc.indexOf(char) + increase) % 26];
    } else if (char in uppercase) {
      answer += uc[(uc.indexOf(char) + increase) % 26];
    } else {
      answer += char;
    }
  }

document.getElementById("response").innerHTML = answer

</script>

I am getting all lowercase 'ccc' or whichever letter corresponds to my var increase

Aucun commentaire:

Enregistrer un commentaire