Search code examples
javascriptstringnumbersnanalphabetical

Getting NaN instead of numbers in javascript


I am trying to get a range of numbers by converting alphabet to numbers and then comparing them with one another to see if they match or not. I can change my approach but I don't understand why is it happening.

function fearNotLetter(str) {
  let left=0
  let right=str.length-1
  for(let i in str) {

    let alphaNum=str.charCodeAt(i) //gives number
    let alphaNum2=str.charCodeAt(i+1) //gives 98 for the first and then NaN for the rest

    console.log(i, alphaNum, alphaNum2)
  }
  

}
fearNotLetter("abce")
fearNotLetter("abcdefghjklmno")


Solution

  • Convert string to integer, for-in loop gives string as key:

    function fearNotLetter(str) {
      let left=0
      let right=str.length-1
      str.split().forEach((char, i) => {
    
        let alphaNum=str.charCodeAt(i) //gives number
        let alphaNum2=str.charCodeAt(i+1) //gives 98 for the first and then NaN for the rest
    
    
      });
      
    
    }
    // fearNotLetter("abce")
    fearNotLetter("abcdefghjklmno")