示例 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
循环用于遍历数组。