JavaScript 精确 判断 数据类型

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiao_yu_liu/article/details/83144003

一、使用 typeof 

typeof 返回对数的类型
 

typeof 123 == 'number'

typeof '123' == 'string'

typeof [1,2,3] == 'object'

typeof {a:1} == 'object'

typeof null == 'object'

typeof function(){} == 'function'

typeof true == 'boolean'

typeof undefined = 'undefined'

结论:typeof 不能用来判断数据是 数组、对象 或者是 null

二、使用 instanceof

暂且不谈

三、使用 Object.prototype.toString.call()
 

Object.prototype.toString.call(123) == '[object Number]'

Object.prototype.toString.call('123') == '[object String]'

Object.prototype.toString.call(true) == '[object Boolean]'

Object.prototype.toString.call(function(){}) == '[object Function]'

Object.prototype.toString.call([1,2,3]) == '[object Array]'

Object.prototype.toString.call({a:1}) == '[object Object]'

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

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

所以,该用那个呢 ? 不需要在说了吧。

所以,该用 Object.prototype.toString.call() ............

var data = '' // 一个你需要验证的数据

Object.prototype.toString.call(data).slice(8,this.length-1) // 返回的值,就是 data 的数据类型

猜你喜欢

转载自blog.csdn.net/xiao_yu_liu/article/details/83144003
今日推荐