• 检测变量类型之typeof,instanceof,Object.prototype.toString


    在JS中有时候是需要对一个变量进行检测的,检测到这个变量是什么类型之后,我们就可以做相应的处理。

    方法一typeof

    typeof方法主要用于基本类型的检测,在检测Boolean,number,undefined,string的时候非常好用。比如:

    1 var test1= 1;
    2 alert(typeof test1);//输出number
    3 var test2 = "";
    4 alert(typeof test2);//输出string
    5 var test3 = undefined;
    6 alert(typeof test3);//输出undefined
    7 var test4 = true;
    8 alert(typeof test4);//输出boolean

    但是用typeof来检测引用类型的时候就没有那么好用了。因为无论你怎么检测,输出都是object类型。这个时候就要用到Object.prototype.toString方法或者instancof。

    方法二instanceof

    var test1 = new Array();
    alert(test1 instanceof Array);//输出true
    var test2 = new String();
    alert(test2 instanceof String);//输出true
    var test3 = {};
    alert(test3 instanceof Object);//输出true
    var test4 = /qwe/;
    alert(test4 instanceof RegExp);//输出true
    var test5 = 1;
    alert(test5 instanceof number);//输出false
    var test6 = "";
    alert(test6 instanceof String);//输出false
    var test7 = true;
    alert(test7 instanceof Boolean);//输出false
    

     instanceof方法对于引用类型很好用,能彻底检测出是什么类型的引用,但是类似于typeof,instanceof对于基本类型就不好用了,结果都会输出false。

    方法三Object.prototype.toString.call

    这个方法就是基于上面两个方法的取其精华,去其糟粕而生成的。

    var test1 = new Array();
    alert(Object.prototype.toString.call(test1));//输出object Array
    var test2 = new String();
    alert(Object.prototype.toString.call(test2));//输出object String
    var test3 = {};
    alert(Object.prototype.toString.call(test3));//输出object Object
    var test4 = /qwe/;
    alert(Object.prototype.toString.call(test4));//输出object RegExp
    var test5 = 1;
    alert(Object.prototype.toString.call(test5));//输出object Number
    var test6 = "";
    alert(Object.prototype.toString.call(test6));//输出object String
    var test7 = true;
    alert(Object.prototype.toString.call(test7));//输出object Boolean

    结合以上3种方法,可以对变量做很彻底的类型检测。

  • 相关阅读:
    SpringCloud(2) 服务注册和发现Eureka Server
    决策树
    python基础6--面向对象基础、装饰器
    python基础5--输入输出、错误与异常
    python基础4--控制流
    python基础3--函数
    python基础2--数据结构(列表List、元组Tuple、字典Dict)
    python基础1--安装、package、数据类型
    Joda-Time开源库
    Maven教程(4)--Maven管理Oracle驱动包
  • 原文地址:https://www.cnblogs.com/178-533/p/7489403.html
Copyright © 2020-2023  润新知