JS中类型判断其实是个很麻烦的事情,特别是在各种情况下都能准确的获得变量的类型是挺不容易的,以下介绍一种比较好记忆的办法
var a = undefined;
var b = null;
var c = true;
var d = 1;
var e = 'string';
var f = function(){}
console.log(typeof a); //undefined
console.log(typeof b); //object
console.log(typeof c); //boolean
console.log(typeof d); //number
console.log(typeof e); //string
console.log(typeof f); //function
var f = [];
var g = function(){};
var h = {};
console.log(f instanceof Array); //true
console.log(g instanceof Function); //true
console.log(h instanceof Object) //true
- 万能方法用 String.prototype.toString.call
var a = undefined;
var b = null;
var c = true;
var d = 1;
var e = 'string';
var f = [];
var g = function(){};
var h = {};
console.log(Object.prototype.toString.call(a)) //[object Undefined]
console.log(Object.prototype.toString.call(b)) //[object Null]
console.log(Object.prototype.toString.call(c)) //[object Boolean]
console.log(Object.prototype.toString.call(d)) //[object Number]
console.log(Object.prototype.toString.call(e)) //[object String]
console.log(Object.prototype.toString.call(f)) //[object Array]
console.log(Object.prototype.toString.call(g)) //[object Function]
console.log(Object.prototype.toString.call(h)) //[object Object]
类库中一般是使用第三种办法判断