【发布时间】: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是字符串,因为for–in迭代属性键,而这些数字属性键是字符串。i + 1执行字符串连接。只需记录i和i + 1是什么就很容易调试。 -
更好的选择:
Array.from("abcdefghjklmno", (char, index, string) => { const alphaNum = char.codePointAt(), alphaNum2 = string.codePointAt(index + 1);…});。请注意,您必须以某种方式处理最后一个索引,在该索引处index + 1不存在。
标签: javascript string numbers nan alphabetical