str [index + 1]在for循环中返回undefined

ark*_*dyt 2 javascript for-loop

为什么会这样?

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])
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 5

问题是for..in循环遍历对象的属性名称.但属性名称始终是字符串,而不是数字.因此,例如,在第一次迭代时:

str[i+1]
Run Code Online (Sandbox Code Playgroud)

评估为

str['0'+1]
Run Code Online (Sandbox Code Playgroud)

是的

str['01']
Run Code Online (Sandbox Code Playgroud)

取而代之的是,投i给一个Number第一:

let str = 'abcd'

for (let i in str) {
    console.log(i, str[i], str[Number(i)+1])
}
Run Code Online (Sandbox Code Playgroud)