当前位置:
尊龙游戏旗舰厅官网 >
前端技术
> javascript
>内容正文
javascript
javascript中四种不同的属性检测方式比较 -尊龙游戏旗舰厅官网
尊龙游戏旗舰厅官网
收集整理的这篇文章主要介绍了
javascript中四种不同的属性检测方式比较
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
javascript中四种不同的属性检测方式比较
1. 用in方法
var o = {x:1}; "x" in o; //true "y" in o; //false "tostring" in o; //true,继承属性可以被检测到 "tostring" in object.prototype; //true,不可枚举的属性可以被检测到
2. hasownproperty()方法
var o = {x:1}; o.hasownproperty("x"); //true o.hasownproperty("y"); //false o.hasownproperty("tostring"); //false,无法检测继承属性 object.prototype.hasownproperty("tostring"); //true,不可枚举的属性可以被检测到3. propertyisenumerable()方法
var o = object.create({y:2}); o.x = 1; o.propertyisenumerable("x"); //true,x是可枚举的属性 o.propertyisenumerable("y"); //false,继承属性,不可枚举 object.prototype.propertyisenumerable("tostring"); //false,不可枚举的属性无法被检测
4. !== undefined方法
var o = {x : 1}; o.x !== undefined; //true,o中有属性x o.tostring !== undefined; //true,继承属性也可以被检测到这种方法的一个弱点是,无法区分不存在的属性和存在但值为undefined的值,如:
var o = {x : undefined}; o.x !== undefined; //false "x" in o; //true注意这里用的是"!=="而不是"!=",因为"!=="可以区分undefined和null。
但有时候不用区分"null"和"undefined",只要判断一个属性不是null或undefined即可。
继承属性是不可枚举的,所以能检测继承属性的,肯定也能检测到不可枚举属性。
×表示无法检测,√表示可以检测
in | √ | √ |
hasownproperty | √ | × |
propertyisenumerable | × | × |
!== | √ | √ |
转载于:https://www.cnblogs.com/menyiin/p/7435755.html
总结
以上是尊龙游戏旗舰厅官网为你收集整理的javascript中四种不同的属性检测方式比较的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇:
- 下一篇: