Judging whether an object has properties in Javascript

 Object.hasOwn() method

Object.hasOwn()method is ES2022newly proposed for alternative Object.prototype.hasOwnProperty()methods. According to the introduction in the MDN documentation : If the specified object has the specified property as its own property, the hasOwn()method returns true; if the property is inherited or does not exist, the method returns false.

let obj = {name: 'aa'};

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

Object.hasOwn()The difference between and Object.hasOwnPeoperty(): Because hasOwnPropertythe method of the instance is Objectobtained from the prototype, if you use Object.create(null)the method to create an object, you can't get hasOwnPropertythis method, and the static method hasOwnas Objectthe method can be called directly Object.

as follows:

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

Guess you like

Origin blog.csdn.net/qq_36657291/article/details/130244624