如何遍历JavaScript中的对象属性

If you have an object, you can’t just iterate it using map(), forEach() or a for..of loop.

如果您有一个对象,则不能仅使用map()forEach()for..of循环对其进行迭代。

You will get errors:

您将得到错误:

const items = {
  'first': new Date(),
  'second': 2,
  'third': 'test'
}

map() will give you TypeError: items.map is not a function:

map()会给您TypeError: items.map is not a function

items.map(item => {})

forEach() will give you TypeError: items.forEach is not a function:

forEach()会给您TypeError: items.forEach is not a function

items.forEach(item => {})

for..of will give you TypeError: items is not iterable:

for..of会给您TypeError: items is not iterable

for (const item of items) {}

So, what can you do to iterate?

那么,您可以做些什么来迭代呢?

for..in is a simpler way:

for..in是一种更简单的方法:

for (const item in items) {
  console.log(item)
}

You can also call Object.entries() to generate an array with all its enumerable properties, and loop through that, using any of the above methods:

您还可以调用Object.entries()生成具有其所有可枚举属性的数组,并使用上述任何一种方法遍历该数组:

Object.entries(items).map(item => {
  console.log(item)
})

Object.entries(items).forEach(item => {
  console.log(item)
})

for (const item of Object.entries(items)) {
  console.log(item)
}

翻译自: https://flaviocopes.com/how-to-iterate-object-properties-javascript/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值