数据类型判断

JS数据类型判断的方法主要有四种方法:typeOf、instanceOf、constructor、Object.prototype.toString.call()
1.Typeof
typeof 能有效检测基本类型,检测引用类型都返回object,其中null属于特殊的引用类型返回
object,function属于特殊引用类型类型不用于存储数据,typeof检测返回function.

   typeof '123'     //  string
   typeof 1        //  number
   typeof true     //  boolean
   typeof Symbol('1')   // symbol
   typeof undefined        // undefined
   typeof null     // object
   typeof {a:1,b:2}    // object 

2、instanceof
2.判断 new 关键字创建的引用数据类型 p instanceof Person
不考虑 null 和 undefined(这两个比较特殊)以对象字面量创建的基本数据类型

[] instanceof Array; //true
{} instanceof Object;//true
new Date() instanceof Date;//true
new RegExp() instanceof RegExp//true
null instanceof Null//报错
undefined instanceof undefined//报错 

3.constructor
constructor似乎完全可以应对基本数据类型和引用数据类型 但如果声明了一个构造函数,并且把他的原型指向了 Array 的原型,所以这种情况下,constructor 也显得力不从心

// String
var str = "字符串";
alert(str.constructor); // function String() { [native code] }
alert(str.constructor === String); // true

// Array
var arr = [1, 2, 3];
alert(arr.constructor); // function Array() { [native code] }
alert(arr.constructor === Array); // true

// Number
var num = 5;
alert(num.constructor); // function Number() { [native code] }
alert(num.constructor === Number); // true 

4、Object.prototype.toString(这个是判断类型最准的方法)

以上三种方法多少都会有一些不能判断的情况。为了保证兼容性,可以通过Object.prototype.toString方法,判断某个对象值属于哪种内置类型。

可以通过toString() 来获取每个对象的类型。为了每个对象都能通过 Object.prototype.toString() 来检测,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,传递要检查的对象作为第一个参数,称为thisArg。

Object.prototype.toString.call('') ;   // [object String]
Object.prototype.toString.call(1) ;    // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object.prototype.toString.call(window) ; //[object global] window是全局对象global的引用 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值