获取 NaN 而不是 javascript 中的数字

Getting NaN instead of numbers in javascript

我试图通过将字母表转换为数字然后将它们相互比较以查看它们是否匹配来获得一系列数字。 我可以改变我的方法,但我不明白为什么会这样。

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

将字符串转换为整数,for-in 循环将字符串作为键:

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

for-in 循环遍历字符串的可枚举属性。它以索引开头:"0""1" 等,但它们将是字符串,因此添加 1 将追加 "1",而 i + 1 将是"01""11""21" 等。当您用这些调用 charCodeAt 时,它们将被转换为数字:11121 等和 charCodeAt returns NaN 用于超出范围的索引值。