===跟==的区别以及类型检测(2012-02-29)

===和==的区别以及类型检测(2012-02-29)

1、 javascript中==和===的区别:

==判断时会进行类型转换再比较,例如:"66" == 66 (true)  0 ==false (true) "0" == false (true)。null == undefined (true)

===判断时不进行类型转换。如果类型都是基本类型,则直接比较其值。如果是引用类型,则比较其引用的地址是否相同。即可以使用===来判断是否属于同一个对象。

 

2、javascript类型检测的方法:

 

typeof:最弱的一种检测方式。typeof对类型的检测只返回以下几种结果:number 、string、boolean、object、function及undefined。对于基本类型的检测还是可以满足的,但是对于对象类型的检测就有问题。检测 typeof null、typeof  {} 、 typeof  window 、typeof []、typeof new 都返回object。对于null类型 可以通过全等比较,value === null。

instanceof:

原理:运算符左侧对象的原型链是否和右侧对象的prototype属性是同一个对象。所以检测存在一个跨域的问题。例如:一个a页面中嵌套一个iframe。iframe引用页面b。a页面有变量 var arr = []。 在b页面中通过parent.arr instanceof Array ,返回结果是false。因为parent.arr的原型链和parent.Array对象的prototype属性引用同一个对象。但是与b页面中的Array对象的prototype属性无关。

Object.prototype.toString.call(o):

Object.prototype.toString( )

       When the toString method is called, the following steps are taken:
       1. Get the [[Class]] property of this object.
       2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
       3. Return Result (2)
即:1、获取对象的类名(对象类型)。2、将结果组装成[object 对象类名]并返回
这个方法即解决了instanceof存在跨页面(跨域)的问题,也解决了typeof局限性的问题。