首页 > 解决方案 > str[index + 1] 在 for 循环中返回 undefined

问题描述

为什么会出现这种情况?

let str = 'sSAo'
console.log(str[0], str[3]) // all good

for (let i in str) {
    // why str[i+1] is undefined ???
    console.log(i, str[i], str[i+1])
}

标签: javascriptfor-loop

解决方案


The problem is that for..in loops iterate over the property names of the object. But property names are always strings, not numbers. Hence, for example, on the first iteration:

str[i+1]

evaluates to

str['0'+1]

which is

str['01']

Instead, cast i to a Number first:

let str = 'abcd'

for (let i in str) {
    console.log(i, str[i], str[Number(i)+1])
}


推荐阅读