数据分析师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.
伊谢尔伦2017-02-21 10:02:09
JS对象是否拥有某属性
两种方式,但稍有区别
1,in 运算符
1 2 3 |
|
可看到无论是name,还是原形链上的toString,都能检测到返回true。
2,hasOwnProperty 方法
1 2 3 |
|
原型链上继承过来的属性无法通过hasOwnProperty检测到,返回false。
需注意的是,虽然in能检测到原型链的属性,但for in通常却不行。
当然重写原型后for in在IE9/Firefox/Safari/Chrome/Opera下是可见的。见:for in的缺陷