zoukankan      html  css  js  c++  java
  • 检测变量类型之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种方法,可以对变量做很彻底的类型检测。

  • 相关阅读:
    互联网协议入门详解(转)
    文件流结尾的EOF详解
    数字签名是什么?
    SSL/TLS协议运行机制的概述(转)
    图解SSL/TLS协议(转)
    RSA算法原理(转)
    HTML代码简写法:Emmet和Haml(转)
    HTML Email 编写指南(转)
    PHP CodeBase: 判断用户是否手机访问
    Spring Data JPA之Derived query
  • 原文地址:https://www.cnblogs.com/178-533/p/7489403.html
Copyright © 2011-2022 走看看