美文网首页
JS 类型判断

JS 类型判断

作者: YXCoder | 来源:发表于2017-12-13 18:32 被阅读0次

    JS中类型判断其实是个很麻烦的事情,特别是在各种情况下都能准确的获得变量的类型是挺不容易的,以下介绍一种比较好记忆的办法

    • 原始类型用 typeof
    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
    
    • 引用类型用 instanceof
    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]
    
    类库中一般是使用第三种办法判断

    相关文章

      网友评论

          本文标题:JS 类型判断

          本文链接:https://www.haomeiwen.com/subject/zcyzixtx.html