キーがオブジェクトに存在するかどうかを確認するJavaScriptプログラム

Javascript

例1:演算子で使用するオブジェクトにキーが存在するかどうかを確認する

// program to check if a key exists

const person = {
    id: 1,
    name: 'John',
    age: 23
}

// check if key exists
const hasKey = 'name' in person;

if(hasKey) {
    console.log('The key exists.');
}
else {
    console.log('The key does not exist.');
}

出力

The key exists.

上記のプログラムでは、 in 演算子は、キーがオブジェクトに存在するかどうかを確認するために使用されます。 ザ・ in 演算子は true 指定されたキーがオブジェクト内にある場合、それ以外の場合は false


例2:hasOwnProperty()を使用して、オブジェクトにキーが存在するかどうかを確認します

// program to check if a key exists

const person = {
    id: 1,
    name: 'John',
    age: 23
}

//check if key exists
const hasKey = person.hasOwnProperty('name');

if(hasKey) {
    console.log('The key exists.');
}
else {
    console.log('The key does not exist.');
}

出力

The key exists.

上記のプログラムでは、 hasOwnProperty() メソッドは、キーがオブジェクトに存在するかどうかを確認するために使用されます。 ザ・ hasOwnProperty() メソッドは true 指定されたキーがオブジェクトにある場合、それ以外の場合は false



Hope this helps!

Source link

コメントを残す

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