js 判断属性是否存在
有两种方法可以判断一个属性是否存在:
- 使用 in 运算符
可以使用 in 运算符来判断一个属性是否存在于对象中。in 运算符返回一个布尔值,表示一个对象是否具有某个属性。例如:
var obj = { name: 'John', age: 20 };
console.log('name' in obj); // true
console.log('gender' in obj); // false
- 使用 hasOwnProperty 方法
也可以使用 hasOwnProperty 方法来判断一个属性是否存在于对象中。hasOwnProperty 方法返回一个布尔值,表示一个对象是否具有指定的属性。例如:
var obj = { name: 'John', age: 20 };
console.log(obj.hasOwnProperty('name')); // true
console.log(obj.hasOwnProperty('gender')); // false
需要注意的是,hasOwnProperty 方法只会检查对象本身是否具有指定的属性,而不会检查其原型链上的属性。如果需要检查原型链上的属性,可以使用 Object.prototype.hasOwnProperty.call 方法。例如:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.gender = 'male';
var john = new Person('John', 20);
console.log(john.hasOwnProperty('name')); // true
console.log(john.hasOwnProperty('gender')); // false
console.log(Object.prototype.hasOwnProperty.call(john, 'gender')); // true
原文地址: https://www.cveoy.top/t/topic/wTL 著作权归作者所有。请勿转载和采集!