JavaScript判断数据类型
JavaScript中判断数据类型的方式有三种:
1.typeof
typeof 1; //"number"
typeof "abc"; //"string"
typeof true; //"boolean"
var a;typeof a;//"undefined"
typeof []; //"object"
typeof {}; //"object"
typeof null; //"object"
typeof function(){}; //"function"
通过上面的例子我们会发现数组,对象以及null通过typeof判断时结果都为"object",我们无法区分它们
2.instanceof
instanceof主要是用来判断对象的类型的
var a=new Object();
a instanceof Object; //true
var b=new Number(1);
b instanceof Object;//true
var c=function(){}
c instanceof Object; //true
3.Object.prototype.toString.call()
Object.prototype.toString.call(1); //"[object Number]"
Object.prototype.toString.call("abc"); //"[object String]"
Object.prototype.toString.call(true); //"[object Boolean]"
Object.prototype.toString.call([]); //"[object Array]"
Object.prototype.toString.call({}); //"[object Object]"
Object.prototype.toString.call(function(){}); //"[object Function]"
Object.prototype.toString.call(undefined); //"[object Undefined]"
Object.prototype.toString.call(null); //"[object Null]"
我们可以看到,每一种数据类型都是唯一区分的,所以推荐使用第三种方式

浙公网安备 33010602011771号