0

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")

2
  • 1
    i are strings since forin iterates property keys and these numeric property keys are strings. i + 1 performs string concatenation. Would’ve been easy to debug by simply logging what i and i + 1 are. Commented Sep 3, 2021 at 8:16
  • 1
    Better alternative: Array.from("abcdefghjklmno", (char, index, string) => { const alphaNum = char.codePointAt(), alphaNum2 = string.codePointAt(index + 1);});. Note that you’ll have to handle the last index, at which the index index + 1 doesn’t exist, in some way or another. Commented Sep 3, 2021 at 8:21

2 Answers 2

1

The for-in loop iterates over the enumerable properties of the string. It starts with the indexes: "0", "1", etc., but they will be strings, so adding 1 will append "1", and i + 1 will be "01", "11", "21" etc. When you call charCodeAt with these, they will be converted to numbers: 1, 11, 21 etc. and charCodeAt returns NaN for out-of range index values.

Sign up to request clarification or add additional context in comments.

Comments

0

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")

5 Comments

so the index i'm getting is the string itsef and not a number?
Using parseInt will NOT fix the code, because i will not only loop over the indexes (as strings), but also some string method names! Just paste this code into Chrome console and see for yourself: const str = "abc"; for (let i in str) { console.log(i, typeof(i)); }
@kol true. so what should be the efficient solution then?
use ForEach loop, updated my answer
forEach is OK, but there is also no problem with using for (let i = 0; i < str.length; i++) :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.