Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

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

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

在本例中,您将学习编写一个 JavaScript 程序,该程序将计算对象中键/属性的数量。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript 对象 JavaScript for...in 循环 Javascript Object.keys()

示例 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 循环将对象中的每个键/值的计数增加 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属性用于统计一个对象的key个数。
Object.keys() 方法返回给定对象自己的可枚举属性名称的数组,即 ["name", "age", "hobbies"]
length 属性返回数组的长度。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4