您好,欢迎访问一九零五行业门户网

分享JavaScript类型之间的比较

javascript的类型原始类型:
number
string
boolean
null
undefined
对象类型:
object
function
array
date
...
隐式转换+/- 运算37 + 7 = 377
37 - 7 = 30
== 运算以下为true:
1.23 == 1.23
0 == false
null == undefined
比较运算===严格等于类型不同,返回false
类型相同,以下为true:
null === null
undefine === null
nan != nan
new object != new obejct
==等于类型相同,同===
类型不同,尝试类型转换比较
null == undefined
number == string 转number
boolean == ? 转number
object == number | string 尝试对象转换为基本类型
其他:false
包装类型为了便于操作基本类型值,js提供了基本类型的自动包装功能,每单读取一个基本类型值的时候,后台就会创建一个对应的基本包装类型的对象,并在调用后自动销毁。
由于基本包装类型和基本类型的含义并不一样,会导致typeof等操作产生不同的结果,不推荐显示实例化基本数据类型
var a = string; alert(a.length);    //6 a.t = 3; alert(a.t);         //undefined
类型检测typeof以下为true:
typeof 100 === “number” typeof true === “boolean” typeof function () {} === “function” typeof(undefined) ) === “undefined” typeof(new object() ) === “object” typeof( [1, 2] ) === “object” typeof(nan ) === “number”   //nan也为number typeof(null) === “object”
instanceofobj instanceof object 利用原型链进行判断,适用于对象间判断。它期望左边是一对象,右边是函数对象或函数构造器。
以下为true:
[1, 2] instanceof array === true new object() instanceof array === false
object.prototype.tostring.apply()object.prototype.tostring.apply([]); === “[object array]”; object.prototype.tostring.apply(function(){}); === “[object function]”; object.prototype.tostring.apply(null); === “[object null]” object.prototype.tostring.apply(undefined); === “[object undefined]” // ie6/7/8 object.prototype.tostring.apply(null) 返回”[object object]”
小结typeof
适合基本类型及function检测,遇到null失效。
[[class]]
通过{}.tostring拿到,适合内置对象和基元类型,遇到null和undefined失效(ie678等返回[object object])。
instanceof
适合自定义对象,也可以用来检测原生对象,在不同iframe和window间检测时失效。
以上就是分享javascript类型之间的比较的详细内容。
其它类似信息

推荐信息