javascript中有六种数据类型:
string;boolean;Array;Object;null;undefined。
如何检测这些数据类型呢,总结方法如下:
一:使用typeof方法
![](https://i-blog.csdnimg.cn/blog_migrate/faee3c9e8894e82d9768f06b475c5ee7.png)
![](https://i-blog.csdnimg.cn/blog_migrate/9cbd1430f3989b61538e46ced47e8e6e.png)
var fn = function(n){
console.log(n);
}
var str = 'string';
var arr = [1,2,3];
var obj = {
a:123,
b:456
};
var num = 1;
var b = true;
var n = null;
var u = undefined;
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
注:通过上面的检测我们发现typeof检测的Array和Object的返回类型都是Object,因此用typeof是无法检测出来数组和对象的。
二:用instanceof检测数组和对象
![](https://i-blog.csdnimg.cn/blog_migrate/3534017648e8e638ef4583401d8c3aad.png)
![](https://i-blog.csdnimg.cn/blog_migrate/32773db35b170d33a2d361fd2539f347.png)
var o = {
'name':'lee'
};
var a = ['red','blue'];
console.log(o instanceof Object);// true
console.log(a instanceof Array);// true
console.log(o instanceof Array);// false
注:instaceof只可以用来判断数组和对象
下面封装一个方法进行改进:
var o = {
'name':'lee'
};
var a = ['reg','blue'];
var getDataType = function(o){
if(o instanceof Array){
return 'Array'
}else if( o instanceof Object ){
return 'Object';
}else{
return 'param is no object type';
}
};
console.log(getDataType(o));//Object。
console.log(getDataType(a));//Array。
三:使用constructor方法
![](https://i-blog.csdnimg.cn/blog_migrate/f918312feedbd97a3d52da050dbafd7e.png)
![](https://i-blog.csdnimg.cn/blog_migrate/ca4e14e8d66618eed8106f2db43f9492.png)
var o = {
'name':'lee'
};
var a = ['red','blue'];
console.log(o.constructor == Object);//true
console.log(a.constructor == Array);//true
四:利用tostring()方法
var o = {
'name':'lee'
};
var a = ['reg','blue'];
function c(name,age){
this.name = name;
this.age = age;
}
var c = new c('kingw','27');
console.log(Object.prototype.toString.call(a));//[object Array]
console.log(Object.prototype.toString.call(o));//[Object Object]
console.log(Object.prototype.toString.call(c));//[Object Object]
//封装一个方法判断数组和对象
function isType(obj){
var type = Object.prototype.toString.call(obj);
if(type == '[object Array]'){
return 'Array';
}else if(type == '[object Object]'){
return "Object"
}else{
return 'param is no object type';
}
}
console.log(isType(o));//Object
console.log(isType(a));//Array
(前端小白,如有错误,欢迎指正~~)