偶尔,您可能需要在 JavaScript 中循环对象。 在 ES6 之前执行此操作的唯一方法是使用 for ... in循环。
for ... in 循环的问题在于它会遍历原型链(Prototype)中的属性。使用 for ... in 循环遍历对象时,需要检查属性是否属于该对象。您可以使用 hasOwnProperty 执行此操作。
for (var property in object) {
if (object.hasOwnProperty(property)) {
// Do things here
}
}
ES6之后,我们不再需要依赖 for ... in 和 hasOwnProperty 。还有更好的方法。
在 JavaScript 中循环对象的更好方法
循环对象的更好方法是首先将对象转换为数组。然后,循环遍历数组。
您可以使用三种方法将对象转换为数组:
- Object.keys
- Object.values
- Object.entries
Object.keys
Object.keys 创建一个包含对象属性的数组。这是一个例子:
const fruits = {
apple: 28,
orange: 17,
pear: 54,
}
const keys = Object.keys(fruits)
console.log(keys) // [apple, orange, pear]
Object.values
Object.values 创建一个数组,其中包含对象中每个属性的值。这是一个例子:
const fruits = {
apple: 28,
orange: 17,
pear: 54,
}
const values = Object.values(fruits)
console.log(values) // [28, 17, 54]
Object.entries
Object.entries 创建一个二维数组。每个内部数组都有两个元素。第一个元素是属性;第二个元素是属性值。
这是一个例子:
const fruits = {
apple: 28,
orange: 17,
pear: 54,
}
const entries = Object.entries(fruits)
console.log(entries)
// [
// [apple, 28],
// [orange, 17],
// [pear, 54]
// ]
我最喜欢的是 Object.entries ,因为你同时获得了键和属性值。
循环数组
一旦将对象通过 Object.keys,Object.values或Object.entries 转换为数组,就可以像使用普通数组一样遍历它。
// Looping through arrays created from Object.keys
const keys = Object.keys(fruits)
for (const key of keys) {
console.log(key)
}
// Results:
// apple
// orange
// pear
如果使用 Object.entries,则可能需要将数组解构为其键和属性。
for (const [fruit, count] of entries) {
console.log(`There are ${count} ${fruit}s`)
}
// Result
// There are 28 apples
// There are 17 oranges
// There are 54 pears
小结
循环对象的更好方法是首先使用这三种方法之一将其转换为数组。
- Object.keys
- Object.values
- Object.entries
然后,像普通数组一样遍历结果。
达维营-前端网