美文网首页
js数据类型之判断

js数据类型之判断

作者: 月下吴刚_c8c7 | 来源:发表于2019-10-12 23:20 被阅读0次

    JS分两种数据类型:zhufeng666

    • 基本数据类型 7 种:

    Number、String、Boolean、Null、 Undefined、Symbol(ES6),这些类型可以直接操作保存在变量中的实际值。

    • 引用数据类型 6 种:

    Object(Object 类型、Array 类型、Date 类型、RegExp 类型、Function 类型、error 等)

    判断数据类型的四种通用方式

    • typeof xxx 用来检测xxx的基础数据类型,有六种结果:
    "number","string","boolean","undefined","function","object"
    
    • xxx instanceof yyy 检测某个实例xxx是否属于某个类yyy(js内置的几个对象类,包装类String,Number,Bolean除外)(在其原型链上),
    1 instanceof Number  ====>false
    new Number(1) instanceof Number  ====>true
    
    • 原型链继承
    function Fn(){定义实例的私有属性}
    Fn.prototype = 父类;(如 [])
    var f = new Fn()   // f此时为一个对象,f就会有自己的私有属性,还有父类的属性
    则有 : f.__proto__ --->Fn.prototype(即arr) --->Array.prototype --> Object.prototype 
    
    
    • xxx.constructor 检测xxx的构造函数,可以检测基本数据类型 ,只找最近的一层,找到后就不再向上找了;找不到再向上找;如果原型中的constructor被重写了,就会检测错误
    /^s/.constructor === RegExp ===>true
    /^s/.constructor === Object   ===>false
    
    • Object.prototype.toString.call(xxx)

    返回 "[object xxx的类型]" ,是最准确最常用的方式,对基础类型和引用类型都有效,不受原型改变的影响

    Object.prototype.toString.call([ ]) === "[object Array]";   // true
    

    数组的单独判断

    • Array.isArray(obj) (ES 5.1推出的,不支持IE6~8)

    Array.isArray([]);  // true
    Array.isArray([1]); // true
    Array.isArray(new Array());
    // 鲜为人知的事实:其实 Array.prototype 也是一个数组。
    Array.isArray(Array.prototype); 
    
    // 下面的函数调用都返回 false
    Array.isArray();
    Array.isArray({});
    Array.isArray(null);
    Array.isArray(undefined);
    Array.isArray(17);
    Array.isArray('Array');
    Array.isArray(true);
    Array.isArray(false);
    Array.isArray({ __proto__: Array.prototype });
    
    ======================================================================

    附记

    • number 的 toString :

    不带参数,将number 转为 string ,(128).toString() ----> '128'
    带参数,转为进制的数后再转为字符串 ,(128).toString(8) ---> '156725', 将128转为8进制
    对于Number,RegExp,String,Date,Function,Array的tiString()都是仅仅将当前数据类型转为字符串;
    对于Math(使用的是Object原型上的toString),Object的toString()会得到当前数据的类型 ----> "[object 类型]"

    • DOM原型链 :

    div.proto --->HTMLDivElement.prototype --> HTMLElement.prototype --> Element.prototype --> Node.proototype --> EventTarget.prototype --> Object.prototype

    null 和undefined 所属的类分别是 Null 和 Undefined,但是浏览器将这两个类保护起来,不允许访问,访问就报错

    相关文章

      网友评论

          本文标题:js数据类型之判断

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