美文网首页
基本数据类型及类型的判断方法

基本数据类型及类型的判断方法

作者: tenro | 来源:发表于2022-07-25 10:00 被阅读0次

    数据类型分为:

    基本数据类型: Number, String, Boolean, Symbol(es6新增), Null, Undefined
    引用数据类型: Object, Function
    

    判断数据类型的方法:

    var a = 1;
    var b = '1';
    var c = true;
    var d = Symbol("kk");
    var e = {a: 1};
    var f = function(){};
    var g = null;
    var h = undefined;
    

    typeof: 常用于对基本数据类型进行判断,返回结果: number, boolean, string, symbol, object, function

    typeof(a);  // 'number'
    typeof(b);  // 'string'
    typeof(c);  // 'boolean'
    typeof(d);  // 'symbol'
    typeof(e);  // 'object'
    typeof(f);  // 'function'
    typeof(g);  // ------------ 'object', js中二进制前三位为0的话会被判断为object类型,而null的二进制都是0
    typeof(h);  // ----------------'undefined'
    

    instanceof: 常用于检测引用类型,基本数据类型无法检测出他们的类型 返回结果: true false

    a instanceof Number     // false
    b instanceof String     // false
    c instanceof Boolean    // false
    d instanceof Symbol     // false
    e instanceof Object     //  true
    f instanceof Function   //  true
    g instanceof Object     // false
    f instanceof Object     // false
    

    constructor: 常用于查看对象的构造函数

    a.constructor == Number     // true
    b.constructor == String     // true
    c.constructor == Boolean    // true
    d.constructor == Symbol     // true
    e.constructor == Object     // true
    f.constructor == Function   // true
    g.constructor == Object     // 报错, 因为null和undefined是无效的对象
    h.constructor == Object     // 报错, 因为null和undefined是无效的对象
    

    Object.prototype.toString: 万能判断

    Object.prototype.toString.call(a)   // '[object Number]'
    Object.prototype.toString.call(b)   // '[object String]'
    Object.prototype.toString.call(c)   // '[object Boolean]'
    Object.prototype.toString.call(d)   // '[object Symbol]'
    Object.prototype.toString.call(e)   // '[object Object]'
    Object.prototype.toString.call(f)   // '[object Function]'
    Object.prototype.toString.call(g)   // '[object Null]'
    Object.prototype.toString.call(h)   // '[object Undefined]'
    

    相关文章

      网友评论

          本文标题:基本数据类型及类型的判断方法

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