美文网首页
Js 之 Object.hasOwn(obj, prop)

Js 之 Object.hasOwn(obj, prop)

作者: small_zeo | 来源:发表于2023-09-18 16:37 被阅读0次

如果指定的对象自身有指定的属性,则静态方法 Object.hasOwn() 返回 true。如果属性是继承的或者不存在,该方法返回 false。

语法

Object.hasOwn(obj, prop)

参数

  • obj
    要测试的JavaScript 实例对象

  • prop
    要测试属性的String类型的名称或者Symbol

返回值

如果指定的对象中直接定义了指定的属性,则返回 true;否则返回 false。

示例

const element = document.getElementById("elt");
const out = document.getElementById("out");
const elementStyle = element.style;

// We loop through all styles (for…of doesn't work with CSStyleDeclaration)
for (const prop in elementStyle) {
  if (Object.hasOwn(elementStyle, prop)) {
    out.textContent += `${
      elementStyle[prop]
    } = '${elementStyle.getPropertyValue(elementStyle[prop])}'\n`;
  }
}

Tips

如果指定的属性是该对象的直接属性——Object.hasOwn() 方法返回 true,即使属性值是 nullundefined。如果属性是继承的或者不存在,该方法返回 false。它不像 in 运算符,这个方法不检查对象的原型链中的指定属性。

参考链接

MDN-hasOwn

相关文章

网友评论

      本文标题:Js 之 Object.hasOwn(obj, prop)

      本文链接:https://www.haomeiwen.com/subject/oougvdtx.html