TypeScript:为什么 for() 循环枚举的值与 Object.forEach() 等不同

发布于 2025-01-20 13:11:15 字数 518 浏览 1 评论 0原文

为什么以下两种在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

木有鱼丸 2025-01-27 13:11:15

正如Andreas在评论中提到的那样,我为循环使用了错误的

更改为循环(而不是in-in)得到了我想要的东西:

for (const s of Object.keys(Side)) {
  console.log(`for...of() ${s}`)
}
// Outputs:
// for...of() LEFT
// for...of() RIGHT

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:

for (const s of Object.keys(Side)) {
  console.log(`for...of() ${s}`)
}
// Outputs:
// for...of() LEFT
// for...of() RIGHT
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文