示例1:使用for … in遍历对象
// program to loop through an object using for...in loop
let 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
循环还将计算继承的属性。
例如,
let student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
let 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
let 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
循环用于循环遍历数组。