美文网首页工作生活
js检测数据类型-来自于三人行慕课

js检测数据类型-来自于三人行慕课

作者: 三人行慕课 | 来源:发表于2019-07-02 21:55 被阅读0次

    原文链接:https://www.3mooc.com/front/articleinfo/227

    1. typeof

    console.log(  typeof '三人行慕课' );   //string

    console.log(  typeof  123   );       //number

    console.log(  typeof function(){} ); //function

    console.log(  typeof []  );          //object

    console.log(  typeof {}  );          //object

    console.log(  typeof null );         //object

    这里可以看到[]、{}、null返回的是一样的,都是object,其实返回的是其原型链最顶端的 Object 类型,但是,这不是我们想要的结果,我们想要的是可以区分的,比如[]返回array之类的,但是在这里typeof就做不到了。

    2. toString

    大家应该对于toString()方法不陌生,其实toString是Object的原型方法,调用方法默认会返回当前对象,这是一个内部属性,其格式为[object xxx],xxx就是类型。

    对于 Object 对象,直接调用 toString()  就能返回 [object Object] 。而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息。

    Object.prototype.toString.call('三人行慕课');     // [object String]

    Object.prototype.toString.call(123);            // [object Number]

    Object.prototype.toString.call(new Function()); // [object Function]

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

    Object.prototype.toString.call(null);           // [object Null]

    3.instanceof

    instanceof 检测的是原型

    console.log(new String('三人行慕课') instanceof String);//true

    console.log([] instanceof Array); //true

    相关文章

      网友评论

        本文标题:js检测数据类型-来自于三人行慕课

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