Search code examples
javascriptarraysundefinedpunctuation

Javascript Punctuation in an array is returning 'undefined'


I am trying to write a small cipher program and need to assemble words along with punctuation. The code works perfectly if I use letters/numbers/special characters ! through ) but isn't working with a comma, a period, or a question mark. I checked and the code is returning undefined, but only for those three punctuations. I wrote a previous version of this code that stripped out all the punctuation which worked fine and now I'm trying to add in the punctuation again.

var alpha = ["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", "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", " ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", ",", ".", "?"];


else if (oldLet == "!") {
    index = 63;
    keyIndex = keyIndex - 1;
} else if (oldLet == ".") {
    index = 84;
    keyIndex = keyIndex - 1;
} else if (oldLet == "?") {
    index = 85;
    keyIndex = keyIndex - 1;
}

var newLet = alpha[index];
alert(newLet);
cipherArray.push(newLet);
}
cipherArray = cipherArray.join("");
document.getElementById("output").innerHTML = cipherArray;
}

I'm completely baffled why the code would work perfectly for letters, numbers, and special characters, but refuses to work properly for punctuation. Any help is appreciated.


Solution

  • Man, I think you got wrong index,

       else if(oldLet == ","){
                    alert("got here 2" + oldLet);
                    index = 83;
                    alert("got here 3" + alpha[index]);
                    keyIndex = keyIndex -1;
                }
                else if(oldLet == "."){
                    index = 84;
                    keyIndex = keyIndex -1;
                }
                else if(oldLet == "?"){
                    index = 85;
                    keyIndex = keyIndex -1;
                }
                
    

    See, it's not 83, 84, 85, it's 73, 74 and 75.

    You can check doing:

    alert(alpha.indexOf(","));