1.js类型判断

144 阅读1分钟

基本类型:boolean number string null undefined

引用类型:Object Function

    var num  = 123;
    var str  = 'abcdef';
    var bool = true;
    var arr  = [1, 2, 3, 4];
    var json = {name:'wenzi', age:25};
    var func = function(){ console.log('this is function'); }
    var und  = undefined;
    var nul  = null;
    var date = new Date();
    var reg  = /^[a-zA-Z]{5,20}$/;
    var error= new Error();

1. 使用typeof检测

    console.log(
        typeof num,
        typeof str,
        typeof bool,
        typeof arr,
        typeof json,
        typeof func,
        typeof und,
        typeof nul,
        typeof date,
        typeof reg,
        typeof error
    );
    // number string boolean object object function undefined object object object object

2. 使用Object.prototype.toString.call

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(und),
    Object.prototype.toString.call(nul),
    Object.prototype.toString.call(date),
    Object.prototype.toString.call(reg),
    Object.prototype.toString.call(error)
);
// '[object Number]' '[object String]' '[object Boolean]' '[object Array]' '[object Object]'
// '[object Function]' '[object Undefined]' '[object Null]' '[object Date]' '[object RegExp]' '[object Error]'

从输出的结果来看,Object.prototype.toString.call(变量)输出的是一个字符串,字符串里有一个数组,第一个参数是Object,第二个参数就是这个变量的类型,而且,所有变量的类型都检测出来了,我们只需要取出第二个参数即可。或者可以使用Object.prototype.toString.call(arr)=="object Array"来检测变量arr是不是数组。

参考文章: