TypeScript:为什么 for() 循环枚举的值与 Object.forEach() 等不同
为什么以下两种在 TypeScript (v4.2.4) 中循环枚举键的方法会产生不同的结果?
enum Side {
LEFT = 'LEFT',
RIGHT = 'RIGHT',
}
// .map(), .reduce(), etc all work as I want and return the string key
Object.keys(Side).forEach(s => console.log(`forEach() ${s}`))
// Outputs:
// forEach() LEFT
// forEach() RIGHT
// but I originally used this approach and was surprised it returned the ordinal/index
for (const s in Object.keys(Side)) {
console.log(`for() ${s}`)
}
// Outputs:
// for() 0
// for() 1
谢谢
Why do the following two approaches to loop over an enum's keys in TypeScript (v4.2.4) yield different results?
enum Side {
LEFT = 'LEFT',
RIGHT = 'RIGHT',
}
// .map(), .reduce(), etc all work as I want and return the string key
Object.keys(Side).forEach(s => console.log(`forEach() ${s}`))
// Outputs:
// forEach() LEFT
// forEach() RIGHT
// but I originally used this approach and was surprised it returned the ordinal/index
for (const s in Object.keys(Side)) {
console.log(`for() ${s}`)
}
// Outputs:
// for() 0
// for() 1
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如Andreas在评论中提到的那样,我为循环使用了错误的
!
更改为循环(而不是in-in)得到了我想要的东西:
As mentioned by Andreas in the comment, I was using the wrong
for
loop!Changing to a for-of loop (as opposed to for-in) got what I wanted: