Javascript中判断对象是否具有属性

 Object.hasOwn()方法

Object.hasOwn()方法是ES2022新提出的,用于替代Object.prototype.hasOwnProperty()的方法。根据MDN文档中的介绍:如果指定的对象具有作为其自身属性的指定属性,则hasOwn()方法返回true;如果该属性是继承的或不存在,则该方法返回false

let obj = {name: 'aa'};

console.log(Object.hasOwn(obj, 'name')); // true
console.log(Object.hasOwn(obj, 'age'));// false

Object.hasOwn()Object.hasOwnPeoperty()的区别:因为实例的hasOwnProperty方法是从Object的原型上拿到的,如果使用Object.create(null)的方式创建一个对象那么就拿不到hasOwnProperty这个方法,而hasOwn作为Object的静态方法是可以直接通过Object来进行调用。

如下:

const obj1 = Object.create(null);
obj1.name = '111';
console.log(obj1.hasOwnProperty('name')); // 报错

const obj2 = Object.create(null);
obj2.name = '222';
console.log(Object.hasOwn(obj2, 'name')); // true

const obj3 = {
    p: 1,
    hasOwnProperty: function () {
        return false
    }
}
console.log(Object.hasOwn(obj3, 'p')); // true

猜你喜欢

转载自blog.csdn.net/qq_36657291/article/details/130244624
今日推荐