JavaScript 程序:计算对象中的键/属性数量

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


示例 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 属性返回数组的长度。


另请阅读

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

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

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

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