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