JS中判断变量类型的方法一共有两种:
① 使用typeof或instance方法(该方法有时候不是很准确)
②使用原生JSh中的Object.prototype.toString.call或jQuery中的$.type(该方法比较精确)
使用:
1.typeof()方法:
var num = 123;
var str = "123";
var nul = null;
var bool = true;
var arr = [1,2,3,4];
var func = function (){};
var un = undefined;
var date = new Date();
var error = new Error();
var json = {name:"lilei"};
console.log(
typeof num,
typeof str,
typeof nul,
typeof bool,
typeof arr,
typeof func,
typeof un,
typeof date,
typeof error,
typeof json
);//输出为 number string object boolean object function undefined object object object
可以看出其中arr,null,date,error,json被检测为Object类型,其他可以被准确的检测出数据类型
2.instance方法
var num = 123;
var str = "123";
var nul = null;
var bool = true;
var arr = [1,2,3,4];
var func = function (){};
var un = undefined;
var date = new Date();
var error = new Error();
var json = {name:"lilei"};
console.log(
num instanceof Number,//false
str instanceof String,//false
bool instanceof Boolean,//false
arr instanceof Array,//true
json instanceof Object,//true
func instanceof Function,//true
un instanceof Object,//false
nul instanceof Object,//false
date instanceof Date,//true
error instanceof Error//true
);
instance方法检测不出number,string和boolean类型,但是当用new方法声明时,可以检测出
3.使用原生JSh中的Object.prototype.toString.call
var num = 123;
var str = "123";
var nul = null;
var bool = true;
var arr = [1,2,3,4];
var func = function (){};
var un = undefined;
var date = new Date();
var error = new Error();
var json = {name:"lilei"};
console.log(
Object.prototype.toString.call(num),
Object.prototype.toString.call(str),
Object.prototype.toString.call(bool),
Object.prototype.toString.call(arr),
Object.prototype.toString.call(json),
Object.prototype.toString.call(func),
Object.prototype.toString.call(un),
Object.prototype.toString.call(nul),
Object.prototype.toString.call(date),
Object.prototype.toString.call(error)
);
// 输出结果[object Number] [object String] [object Boolean] [object Array] [object Object] [object Function] [object Undefined] [object Null] [object Date] [object Error]
输出的结果中第二个参数是该变量的类型,可以看出所有变脸都可以检测出其类型
4.jQuery中的$.type
var num = 123;
var str = "123";
var nul = null;
var bool = true;
var arr = [1,2,3,4];
var func = function (){};
var un = undefined;
var date = new Date();
var error = new Error();
var json = {name:"lilei"};
// 使用jQuery的$.type
console.log(
$.type(num),
$.type(str),
$.type(bool),
$.type(arr),
$.type(json),
$.type(func),
$.type(un),
$.type(nul),
$.type(date),
$.type(error)
);
// 输出结果number string boolean array object function undefined null date error
此方法可以直接输出变量的类型
对比下来还是jQuery的$.type方法比较好用