跳到主要内容

JavaScript 程序:遍历一个对象

要理解这个示例,你应该了解以下JavaScript编程主题的知识:

示例1:使用for...in遍历对象

// 使用for...in循环遍历对象的程序

const student = {
name: "John",
age: 20,
hobbies: ["reading", "games", "coding"],
};

// 使用for...in
for (let key in student) {
let 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",
};

// 继承属性
student.__proto__ = person;

for (let key in student) {
let 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遍历对象

// 使用for...in循环遍历对象的程序

const student = {
name: "John",
age: 20,
hobbies: ["reading", "games", "coding"],
};

// 使用Object.entries
// 使用for...of循环
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循环用于遍历数组。