【问题标题】:Getting NaN instead of numbers in javascript [duplicate]在javascript中获取NaN而不是数字[重复]
【发布时间】:2021-11-01 14:22:38
【问题描述】:

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

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

【问题讨论】:

  • i 是字符串,因为 forin 迭代属性键,而这些数字属性键是字符串。 i + 1 执行字符串连接。只需记录 ii + 1 是什么就很容易调试。
  • 更好的选择:Array.from("abcdefghjklmno", (char, index, string) => { const alphaNum = char.codePointAt(), alphaNum2 = string.codePointAt(index + 1);});。请注意,您必须以某种方式处理最后一个索引,在该索引处index + 1 不存在。

标签: javascript string numbers nan alphabetical


【解决方案1】:

将字符串转换为整数,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")

【讨论】:

  • 所以我得到的索引是字符串 itsef 而不是数字?
  • 使用 parseInt 不会修复代码,因为i 不仅会循环索引(作为字符串),还会循环一些字符串方法名称!只需将此代码粘贴到 Chrome 控制台中,然后自己查看:const str = "abc"; for (let i in str) { console.log(i, typeof(i)); }
  • @kol 是真的。那么什么是有效的解决方案呢?
  • 使用 ForEach 循环,更新我的答案
  • forEach 可以,但是使用for (let i = 0; i < str.length; i++) 也没有问题 :)
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2016-08-09
    • 2015-08-28
    • 2012-08-10
    • 2015-12-30
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    相关资源
    最近更新 更多