示例 1:使用 for...in 循环计算对象中键的数量
// program to count the number of keys/properties in an object
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
let count = 0;
// loop through each key/value
for(let key in student) {
// increase the count
++count;
}
console.log(count);
输出
3
上面的程序使用 for...in
循环计算对象中键/属性的数量。
count
变量最初为 0。然后,for...in
循环会为对象中的每个键/值将 count 加 1。
注意:在使用 for...in
循环时,它还会计算继承的属性。
例如,
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
const person = {
gender: 'male'
}
student.__proto__ = person;
let count = 0;
for(let key in student) {
// increase the count
++count;
}
console.log(count); // 4
如果你只想遍历对象自身的属性,可以使用 hasOwnProperty() 方法。
if (student.hasOwnProperty(key)) {
++count:
}
示例 2:使用 Object.key() 计算对象中键的数量
// program to count the number of keys/properties in an object
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
// count the key/value
const result = Object.keys(student).length;
console.log(result);
输出
3
在上面的程序中,Object.keys() 方法和 length
属性用于计算对象中键的数量。
Object.keys()
方法返回一个给定对象自身可枚举属性名称的 数组,即 ["name", "age", "hobbies"]。
length
属性返回数组的长度。
另请阅读