JavaScript代码执行时得到NaN而非数字的原因是什么?
NaN出现的原因
for...in遍历字符串得到的索引i是字符串类型,比如遍历"abce"得到的i依次是"0"、"1"、"2"、"3",执行i+1时会触发字符串拼接逻辑,比如"0"+1得到的是"01"而非数字1,当拼接后的字符串不存在对应索引时,charCodeAt就会返回NaN。- 就算把i转成数字,遍历到最后一个字符(索引为
str.length-1)时,i+1超出了字符串的最大索引范围,charCodeAt接收超出范围的下标时,默认返回NaN。
修正后的实现代码
你要实现的查找缺失连续字母的逻辑可以调整为如下写法:
function fearNotLetter(str) { // 只遍历到倒数第二个字符,避免下标越界 for(let i = 0; i < str.length - 1; i++) { const currentCode = str.charCodeAt(i) const nextCode = str.charCodeAt(i+1) // 相邻字符编码差大于1说明中间有缺失 if(nextCode - currentCode > 1) { return String.fromCharCode(currentCode + 1) } } // 所有字母连续时返回undefined return undefined } // 测试 console.log(fearNotLetter("abce")) // 输出d console.log(fearNotLetter("abcdefghjklmno")) // 输出i
内容的提问来源于stack exchange,提问作者Shahid Alam
相关产品推荐
相关产品推荐

