做二手房网站,室内设计公司的运营模式,网站维护工作计划,茂名一站式网站建设报价Object.hasOwn() 如果指定的对象自身有指定的属性#xff0c;则静态方法 Object.hasOwn() 返回 true。如果属性是继承的或者不存在#xff0c;该方法返回 false。 备注#xff1a; Object.hasOwn() 旨在取代 Object.prototype.hasOwnProperty()。 **语法#xff1a;**Objec…Object.hasOwn() 如果指定的对象自身有指定的属性则静态方法 Object.hasOwn() 返回 true。如果属性是继承的或者不存在该方法返回 false。 备注 Object.hasOwn() 旨在取代 Object.prototype.hasOwnProperty()。 **语法**Object.hasOwn(obj, prop) 参数说明 obj - 要测试的 JavaScript 实例对象。 prop - 要测试属性的 String 类型的名称或者 Symbol。 返回值 如果指定的对象自身有指定的属性则返回 true否则返回 false。 描述 如果指定的属性是该对象的直接属性——Object.hasOwn() 方法返回 true即使属性值是 null 或 undefined。如果属性是继承的或者不存在该方法返回 false。它不像 in 运算符这个方法不检查对象的原型链中的指定属性。
例子一 let obj1 {name:光头强}let result1 Object.hasOwn(obj1,name)let result2 Object.hasOwn(obj1,age)console.log(result1) // 打印结果 trueconsole.log(result2) // 打印结果 false例子二
const example {};
Object.hasOwn(example, prop); // false——目标对象的属性 prop 未被定义example.prop exists;
Object.hasOwn(example, prop); // true——目标对象的属性 prop 已被定义example.prop null;
Object.hasOwn(example, prop); // true——目标对象本身的属性存在值为 nullexample.prop undefined;
Object.hasOwn(example, prop); // true——目标对象本身的属性存在值为 undefined也可以检查数组索引是否存在 例子三
const fruits [光头强, 熊大, 熊二, 吉吉国王];
Object.hasOwn(fruits, 3); // true (吉吉国王)
Object.hasOwn(fruits, 4); // false——没有定义的注意官方说明 建议使用此方法替代 Object.prototype.hasOwnProperty()因为它适用于使用 Object.create(null) 创建的对象以及重写了继承的 hasOwnProperty() 方法的对象。尽管可以通过在外部对象上调用 Object.prototype.hasOwnProperty() 解决这些问题但是 Object.hasOwn() 更加直观。