zoukankan      html  css  js  c++  java
  • js问题记录(二) -- 关于typeof,instanceof,Object.prototype.toString.call()

    1、关于typeof

    typeof(item):返回item的数据类型

    js有基本数据类型number,string,null,undefined,boolean,symbol等,其余为引用类型object的变形

    由下示例可以看出:
    typeof():可以检测出:string,function,undefined,number,boolean等类型
    但不可以检测:null,Array,Date,RegExp等对象的类型
    代码示例:

        <script>
            var str = '123',
                arr = [],
                fun = function() {},
                n = null,
                un = undefined,
                number = 123,
                flag = true,
                date = new Date(),
                reg = new RegExp();
            console.log(typeof(str)); //string
            console.log(typeof(arr)); //object
            console.log(typeof(fun)); //function
            console.log(typeof(n)); //object
            console.log(typeof(un)); //undefined
            console.log(typeof(number)); //number
            console.log(typeof(flag)); //boolean
            console.log(typeof(date)); //object
            console.log(typeof(reg)); //object
        </script>
    

    2、关于instanceof

    A instanceof B:判断A是否是B的实例,返回boolean类型;

    原理:检查一个对象A的原型链中是否有构造函数B的prototype属性

    代码示例:

        <script>
            console.log(arr instanceof Array); //true
            console.log(str instanceof String); //false
            str = new String(123);
            console.log(str instanceof String); //true
            console.log(date instanceof Date); //true
            console.log(reg instanceof RegExp); //true
        </script>
    

    3、关于Object.prototype.toString.call()

    Object上的toString()返回当前this的详细信息

    代码示例:

        <script>
            console.log(Object.prototype.toString.call(str)); //[object String]
            console.log(Object.prototype.toString.call(arr)); //[object Array]
            console.log(Object.prototype.toString.call(n)); //[object Null]
            console.log(Object.prototype.toString.call(un)); //[object Undefined]
            console.log(Object.prototype.toString.call(number)); //[object Number]
            console.log(Object.prototype.toString.call(flag)); //[object Boolean]
            console.log(Object.prototype.toString.call(date)); //[object Date]
            console.log(Object.prototype.toString.call(reg)); //[object RegExp]
    
            let type = Object.prototype.toString.call(str);
            type = type.slice(8, type.length - 1);
            console.log(type);//String
        </script>
    
  • 相关阅读:
    Eclipse插件
    Android res文件夹下新建layout文件夹出错:invalid resource directory name
    Java笔记一:斐波那契数列
    Android应用的启动界面
    android短信系列之实现发送短信,并获得发送报告与接收报告
    转:android 使用html5作布局文件
    ubuntu10.10 全自动安装微软雅黑字体
    gcswf32.dll已停用
    Android连接真机之中兴
    在Servlet中连接Access
  • 原文地址:https://www.cnblogs.com/Zxq-zn/p/12094736.html
Copyright © 2011-2022 走看看