js有5种基本数据类型 Undefined , Null , Boolean , Number , String 和一种引用类型Object,下面我们就来一一看穿,哦不,识别他们。
- typeof
前面5种虽多,但是是基本类型,也容易识别,typeof 操作符就能差不多把他们都识别了,
null 不服的站了出来:“能识别我么?”,typeof这下犯难了:"你,你你先坐下。" typeof对Object基本上是脸盲的,除了function之外看谁都是Object, 数组是对象,日期对象是对象,正则是对象,对象也是对象。都特么是对象,typeof 范晕了,只好去请教表哥 instanceof
console.log(typeof "hello");//"string"console.log(typeof 666);//"number"console.log(typeof true);//"boolean"console.log(typeof undefined);//"undefined"console.log(typeof null);//"object"
console.log(typeof {name: "hello"});//"object"console.log(typeof function(){});//"function"console.log(typeof []);//"object"console.log(typeof new Date);//"object"console.log(typeof /\d/);//"object"function Person(){};console.log(typeof new Person);//"object"
简单说,记住两点就好了1.typeof可识别出null之外的基本类型 2.不能识别除function之外的具体对象类型
2. instanceof
浅谈js数据类型识别方法
原文地址:http://www.cnblogs.com/renbo/p/7538465.html