js中有7种数据类型,其中
三种基本类型:Number、String、Boolean
两种引用类型:Object、Array
两种特殊类型:undefined、null
- 1.判断boolean类型的不再多说,我们都知道undefined、null、NaN、0、’'这几种大都是false,其余都是true
- 2.typeof,他无法判断数组和对象,返回的都是Object
console.log(typeof str);//string
console.log(typeof arr);//object
console.log(typeof obj);//object
console.log(typeof num);//number
console.log(typeof b);//boolean
console.log(typeof n);//null是一个空的对象
console.log(typeof u);//undefined
console.log(typeof fn);//function
- 3.instanceof ,可以区分数组和对象,但是无法判断String、boolean
// 我们定义了arr是数组,obj是对象的变量
console.log(obj instanceof Object);// true
console.log(arr instanceof Array);// true
console.log(obj instanceof Array);// false
- 4.constructor也能判断是数组还是对象
console.log(obj.constructor == Object);//true
console.log(arr.constructor == Array);//true
- 5.利用tostring()方法,这个方法是最佳的方案,可判断对象、数组、布尔、字符串
// arr、obj、fn分别是我提前定义的数组、对象、函数
console.log(Object.prototype.toString.call(arr));//[object Array],结果是字符串
console.log(Object.prototype.toString.call(obj));//[Object Object]
console.log(Object.prototype.toString.call(fn));//[Object Function]