search

Home  >  Q&A  >  body text

如何判断JS对象是否拥有某属性?

如何判断JS对象是否拥有某属性?

baby不要哭泣baby不要哭泣2933 days ago727

reply all(2)I'll reply

  • 数据分析师

    数据分析师2017-10-01 00:25:58

    How to determine whether a JS object has a certain attribute? -PHP Chinese website Q&A-How to determine whether a JS object has a certain attribute? -PHP Chinese website Q&A

    Let’s take a look and learn.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-02-21 10:02:09

    JS对象是否拥有某属性

    两种方式,但稍有区别

    1,in 运算符

    var obj = {name:'jack'};
    alert('name' in obj); // --> true
    alert('toString' in obj); // --> true

    可看到无论是name,还是原形链上的toString,都能检测到返回true。

    2,hasOwnProperty 方法

    var obj = {name:'jack'};
    obj.hasOwnProperty('name'); // --> true
    obj.hasOwnProperty('toString'); // --> false

    原型链上继承过来的属性无法通过hasOwnProperty检测到,返回false。

    需注意的是,虽然in能检测到原型链的属性,但for in通常却不行。

    当然重写原型后for in在IE9/Firefox/Safari/Chrome/Opera下是可见的。见:for in的缺陷


    reply
    0
  • Cancelreply