オブジェクト内のキー/プロパティの数をカウントする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 ループはカウントを増やします 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 プロパティは、配列の長さを返します。



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です