javascript - 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])
}
解决方案
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])
}
推荐阅读
- r - 从具有重复值的数据框中删除列
- flutter - Flutter 自定义导航高亮选中页面
- python - 为什么我的脚本调用 python 解释器?
- javascript - 无法在 Wordpress 中将脚本排入队列
- r - 将变异应用于 R 中的数据帧:重复一个额外的步骤并导致错误
- python - 如何正确处理tensorflow RNN中的一热编码和多维数据
- google-chrome - Blazor 在 Chrome 中不工作,但在 Edge 中工作
- qt - 如何在按钮单击时切换 svg 图标 - 使用 QT C++
- php - Slim 框架:无法使用 JWT 令牌
- vba - Access VBA中字符串的列表框值(用逗号分隔)