「JavaScript」hasOwnProperty() メソッドでプロパティ存在判定サンプル
書式
obj.hasOwnProperty(prop)
オブジェクト自身が(継承されていない)指定されたプロパティを持っているかどうかを示す真偽値を返します。
使用例
const obj = {};
obj.age = 42;
obj.name ="user002"
console.log("ageプロパティ: "+obj.hasOwnProperty('age'));
console.log("nameプロパティ: "+obj.hasOwnProperty('name'));
console.log("addrプロパティ: "+obj.hasOwnProperty('addr'));
const obj = {};
obj.age = 42;
obj.name ="user002"
console.log("ageプロパティ: "+obj.hasOwnProperty('age'));
console.log("nameプロパティ: "+obj.hasOwnProperty('name'));
console.log("addrプロパティ: "+obj.hasOwnProperty('addr'));
const obj = {}; obj.age = 42; obj.name ="user002" console.log("ageプロパティ: "+obj.hasOwnProperty('age')); console.log("nameプロパティ: "+obj.hasOwnProperty('name')); console.log("addrプロパティ: "+obj.hasOwnProperty('addr'));
結果
> “ageプロパティ: true"
> “nameプロパティ: true"
> “addrプロパティ: false"