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")
  • 1
    `i` are strings since `for`–`in` 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. – Sebastian Simon Sep 03 '21 at 08: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. – Sebastian Simon Sep 03 '21 at 08:21

2 Answers2

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.

kol
  • 27,881
  • 12
  • 83
  • 120
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")
Harshit Rastogi
  • 1,996
  • 1
  • 10
  • 19
  • so the index i'm getting is the string itsef and not a number? – Shahid Alam Sep 03 '21 at 08:25
  • 1
    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 Sep 03 '21 at 08:27
  • @kol true. so what should be the efficient solution then? – Shahid Alam Sep 03 '21 at 08:28
  • 1
    use ForEach loop, updated my answer – Harshit Rastogi Sep 03 '21 at 08:29
  • `forEach` is OK, but there is also no problem with using `for (let i = 0; i < str.length; i++)` :) – kol Sep 03 '21 at 08:32