Javascript类型判断

来源:互联网 发布:淘宝十大女模特排名 编辑:程序博客网 时间:2024/06/01 07:50

Javascript里有几种方法可以判断对象的类型

1) typeof 但其对所有引用对象返回的都是 object 类型  (typeof 只能返回如下结果),所以用typeof判断变量的类型是有局限性的, 用得较多是判断变量是否存在,但是 typeof(null)返回的是object。 所以判断变量是否存在也是有点小问题的。


typeof(3)
"number"


typeof(false)
"boolean"


typeof("sds")
"string"


typeof(function test(){})
"function"


typeof([])
"object"


typeof(null)
"object"


typeof(undefined)
"undefined"


typeof({})
"object"


2) Object.prototype.toString.call() 利用Object原型的toString方法获取类型, 但这个方法也有局限性, 在IE7,8,9里Object.prototype.toString.call(null) , Object.prototype.toString.call(undefined)  都返回  "[object Object]"


Object.prototype.toString.call(123)
"[object Number]"  //强制转化成Number类型 返回


Object.prototype.toString.call(false)
"[object Boolean]" //强制转化成Number类型 返回

Object.prototype.toString.call("srsf")
"[object String]"


Object.prototype.toString.call(null)
"[object Null]"


Object.prototype.toString.call([])
"[object Array]"


Object.prototype.toString.call({})
"[object Object]"


Object.prototype.toString.call(undefined)
"[object Undefined]"


Object.prototype.toString.call(function test(){})
"[object Function]"

0 0
原创粉丝点击