示例 1:使用 for...in 循环遍历对象
// program to loop through an object using for...in loop
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
// using for...in
for (let key in student) {
let value;
// get the value
value = student[key];
console.log(key + " - " + value);
}
输出
name - John age - 20 hobbies - ["reading", "games", "coding"]
在上面的示例中,for...in
循环用于遍历 student
对象。
通过使用 student[key]
来访问每个键的值。
注意:for...in
循环也会计算继承的属性。
例如,
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
const person = {
gender: 'male'
}
// inheriting property
student.__proto__ = person;
for (let key in student) {
let value;
// get the value
value = student[key];
console.log(key + " - " + value);
}
输出
name - John age - 20 hobbies - ["reading", "games", "coding"] gender - male
如果需要,您可以使用 hasOwnProperty() 方法仅遍历对象自身的属性。
if (student.hasOwnProperty(key)) {
++count:
}
示例 2:使用 Object.entries 和 for...of 循环遍历对象
// program to loop through an object using for...in loop
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
// using Object.entries
// using for...of loop
for (let [key, value] of Object.entries(student)) {
console.log(key + " - " + value);
}
输出
name - John age - 20 hobbies - ["reading", "games", "coding"]
在上面的程序中,使用 Object.entries()
方法和 for...of 循环来遍历对象。
Object.entries()
方法返回给定对象的键/值对的 数组。for...of
循环用于遍历数组。