JavaScript 遍历对象程序

要理解此示例,您应了解以下 JavaScript 编程 主题


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

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战