搜索
首页web前端前端问答【js基础】变量类型判断
【js基础】变量类型判断Jun 11, 2018 pm 10:36 PM
前端类型判断

类型判断方法比较:

这里写图片描述

如果需要想详细了解,请看下文:

注:原封不动复制备份,防止删帖

在JavaScript中,有5种基本数据类型和1种复杂数据类型,基本数据类型有:Undefined, Null, Boolean, Number和String;复杂数据类型是Object, Object中还细分了很多具体的类型,比如:Array, Function, Date等等。今天我们就来探讨一下,使用什么方法判断一个出一个变量的类型。

在讲解各种方法之前,我们首先定义出几个测试变量,看看后面的方法究竟能把变量的类型解析成什么样子,以下几个变量差不多包含了我们在实际编码中常用的类型。

var num  = 123; 
var str  = ‘abcdef’; 
var bool = true; 
var arr  = [1, 2, 3, 4]; 
var json = {name:’wenzi’, age:25}; 
var func = function(){ console.log(‘this is function’); } 
var und  = undefined; 
var nul  = null; 
var date = new Date(); 
var reg  = /^[a-zA-Z]{5,20}$/; 
var error= new Error();


1. 使用typeof检测
我们平时用的最多的就是用 typeof检测变量类型了。这次,我们也使用 typeof检测变量的类型:

console.log( 

    typeof num,  

    typeof str,  

    typeof bool,  

    typeof arr,  

    typeof json,  

    typeof func,  

    typeof und,  

    typeof nul,  

    typeof date,  

    typeof reg,  

    typeof error 
); 
// number string boolean object object function undefined object object object object


从输出的结果来看,arr, json, nul, date, reg, error 全部被检测为 object类型,其他的变量能够被正确检测出来。当需要变量是否是 number,  string,  boolean,  function,  undefined, json类型时,可以使用typeof进行判断。其他变量是判断不出类型的,包括null。

还有,typeof是区分不出 array和 json类型的。因为使用typeof这个变量时,array和json类型输出的都是 object。

  1. 使用instance检测
    在 JavaScript 中,判断一个变量的类型尝尝会用 typeof 运算符,在使用 typeof 运算符时采用引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回 “object”。ECMAScript 引入了另一个 Java 运算符 instanceof 来解决这个问题。instanceof 运算符与 typeof 运算符相似,用于识别正在处理的对象的类型。与 typeof 方法不同的是,instanceof 方法要求开发者明确地确认对象为某特定类型。例如:

function Person(){
} var Tom = new Person(); console.log(Tom instanceof Person); // true


我们再看看下面的例子:

function Person(){
} function Student(){
} Student.prototype = new Person(); var John = new Student(); console.log(John instanceof Student); // true console.log(John instancdof Person);  // true instanceof还能检测出多层继承的关系。
好了,我们来使用 instanceof检测上面的那些变量:
console.log( 
    num instanceof Number, 
    str instanceof String, 
    bool instanceof Boolean, 
    arr instanceof Array, 
    json instanceof Object, 
    func instanceof Function, 
    und instanceof Object, 
    nul instanceof Object, 
    date instanceof Date, 
    reg instanceof RegExp, 
    error instanceof Error ) // num : false  // str : false  // bool : false  // arr : true  // json : true  // func : true  // und : false  // nul : false  // date : true  // reg : true  // error : true


从上面的运行结果我们可以看到,num, str和bool没有检测出他的类型,但是我们使用下面的方式创建num,是可以检测出类型的:

var num = new Number(123); 
var str = new String(‘abcdef’); 
var boolean = new Boolean(true);


同时,我们也要看到,und和nul是检测的Object类型,才输出的true,因为js中没有 Undefined和 Null的这种全局类型,他们und和nul都属于Object类型,因此输出了true。

  1. 使用constructor检测
    在使用 instanceof检测变量类型时,我们是检测不到 number, ‘string’,  bool的类型的。因此,我们需要换一种方式来解决这个问题。

constructor本来是原型对象上的属性,指向构造函数。但是根据实例对象寻找属性的顺序,若实例对象上没有实例属性或方法时,就去原型链上寻找,因此,实例对象也是能使用constructor属性的。

我们先来输出一下 num.constructor的内容,即数字类型的变量的构造函数是什么样子的:

function Number() { [native code] }
我们可以看到它指向了 Number的构造函数,因此,我们可以使用 num.constructor==Number来判断num是不是Number类型的,其他的变量也类似:

function Person(){
} var Tom = new Person();
// undefined和null没有constructor属性 console.log( 
    Tom.constructor==Person, 
    num.constructor==Number, 
    str.constructor==String, 
    bool.constructor==Boolean, 
    arr.constructor==Array, 
    json.constructor==Object, 
    func.constructor==Function, 
    date.constructor==Date, 
    reg.constructor==RegExp, 
    error.constructor==Error );


// 所有结果均为true
从输出的结果我们可以看出,除了undefined和null,其他类型的变量均能使用 constructor判断出类型。

不过使用constructor也不是保险的,因为constructor属性是可以被修改的,会导致检测出的结果不正确,例如:

function Person(){
} function Student(){
} Student.prototype = new Person(); var John = new Student(); console.log(John.constructor==Student); // false console.log(John.constructor==Person);  // true


在上面的例子中,Student原型中的constructor被修改为指向到Person,导致检测不出实例对象John真实的构造函数。

同时,使用instaceof和construcor,被判断的array必须是在当前页面声明的!比如,一个页面(父页面)有一个框架,框架中引用了一个页面(子页面),在子页面中声明了一个array,并将其赋值给父页面的一个变量,这时判断该变量,Array == object.constructor;会返回false;
原因:
1、array属于引用型数据,在传递过程中,仅仅是引用地址的传递。
2、每个页面的Array原生对象所引用的地址是不一样的,在子页面声明的array,所对应的构造函数,是子页面的Array对象;父页面来进行判断,使用的Array并不等于子页面的Array;切记,不然很难跟踪问题!

  1. 使用Object.prototype.toString.call
    我们先不管这个是什么,先来看看他是怎么检测变量类型的:

console.log( 

    Object.prototype.toString.call(num), 

    Object.prototype.toString.call(str), 

    Object.prototype.toString.call(bool), 

    Object.prototype.toString.call(arr), 

    Object.prototype.toString.call(json), 

    Object.prototype.toString.call(func), 

    Object.prototype.toString.call(und), 

    Object.prototype.toString.call(nul), 

    Object.prototype.toString.call(date), 

    Object.prototype.toString.call(reg), 

    Object.prototype.toString.call(error) 
);


// ‘[object Number]’ ‘[object String]’ ‘[object Boolean]’ ‘[object Array]’ ‘[object Object]’
// ‘[object Function]’ ‘[object Undefined]’ ‘[object Null]’ ‘[object Date]’ ‘[object RegExp]’ ‘[object Error]’
从输出的结果来看, Object.prototype.toString.call(变量)输出的是一个字符串,字符串里有一个数组,第一个参数是Object,第二个参数就是这个变量的类型,而且,所有变量的类型都检测出来了,我们只需要取出第二个参数即可。或者可以使用 Object.prototype.toString.call(arr)==”object Array”来检测变量arr是不是数组。

我们现在再来看看ECMA里是是怎么定义 Object.prototype.toString.call的:

Object.prototype.toString( ) When the toString method is called, the following steps are taken:
1. Get the [[Class]] property of this object.
2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
3. Return Result (2)
上面的规范定义了Object.prototype.toString的行为:首先,取得对象的一个内部属性[[Class]],然后依据这个属性,返回一个类似于”[object Array]”的字符串作为结果(看过ECMA标准的应该都知道,[[]]用来表示语言内部用到的、外部不可直接访问的属性,称为“内部属性”)。利用这个方法,再配合call,我们可以取得任何对象的内部属性[[Class]],然后把类型检测转化为字符串比较,以达到我们的目的。

  1. jquery中

    .type的接口,来让我们检测变量的类型:

console.log( 
.type(str), 
.type(arr), 
.type(func), 
.type(nul), 
.type(reg), 
    $.type(error) );


// number string boolean array object function undefined null date regexp error
看到输出结果,有没有一种熟悉的感觉?对,他就是上面使用 Object.prototype.toString.call(变量)输出的结果的第二个参数呀。


我们这里先来对比一下上面所有方法检测出的结果,横排是使用的检测方法, 竖排是各个变量:

类型判断    typeof  instanceof  constructor toString.call  

type输出的结果真的很像。我们来看看jquery(2.1.2版本)内部是怎么实现$.type方法的:


// 实例对象是能直接使用原型链上的方法的 var class2type = {}; var toString = class2type.toString;
// 省略部分代码…
type: function( obj ) { 
    if ( obj == null ) { 
        return obj + “”; 
    } 
    // Support: Android<4.0, iOS<6 (functionish RegExp) 
    return (typeof obj === “object” || typeof obj === “function”) ? 
        (class2type[ toString.call(obj) ] || “object”) : 
        typeof obj; },
// 省略部分代码…
// Populate the class2type map jQuery.each(“Boolean Number String Function Array Date RegExp Object Error”.split(” “), function(i, name) { 
    class2type[ “[object ” + name + “]” ] = name.toLowerCase(); });


我们先来看看jQuery.each的这部分:

// Populate the class2type map
jQuery.each(“Boolean Number String Function Array Date RegExp Object Error”.split(” “), function(i, name) {
   class2type[ “[object ” + name + “]” ] = name.toLowerCase();
});

//循环之后,class2type的值是:  

class2type = { 

    ‘[object Boolean]’ : ‘boolean’,  

    ‘[object Number]’  : ‘number’, 

    ‘[object String]’  : ‘string’, 

    ‘[object Function]’: ‘function’, 

    ‘[object Array]’   : ‘array’, 

    ‘[object Date]’    : ‘date’, 

    ‘[object RegExp]’  : ‘regExp’, 

    ‘[object Object]’  : ‘object’, 

    ‘[object Error]’   : ‘error’ 
}


再来看看 type方法:

// type的实现 
type: function( obj ) { 

    // 若传入的是null或undefined,则直接返回这个对象的字符串 

    // 即若传入的对象obj是undefined,则返回”undefined” 

    if ( obj == null ) { 

        return obj + “”; 

    } 

    // Support: Android<4.0, iOS<6 (functionish RegExp) 

    // 低版本regExp返回function类型;高版本已修正,返回object类型 

    // 若使用typeof检测出的obj类型是object或function,则返回class2type的值,否则返回typeof检测的类型 

    return (typeof obj === “object” || typeof obj === “function”) ? 

        (class2type[ toString.call(obj) ] || “object”) : 

        typeof obj; 
}


当 typeof obj === “object” || typeof obj === “function”时,就返回 class2type[ toString.call(obj)。到这儿,我们就应该明白为什么Object.prototype.toString.call和$.type那么像了吧,其实jquery中就是用 Object.prototype.toString.call实现的,把’[object Boolean]’类型转成’boolean’类型并返回。若class2type存储的没有这个变量的类型,那就返回”object”。
除了”object”和”function”类型,其他的类型则使用typeof进行检测。即 number,  string,  boolean类型的变量,使用typeof即可。

本文讲解了【js基础】变量类型判断 更多相关内容请关注php中文网。

相关推荐:

JQuery中DOM操作——wrap

django 使用 request 获取浏览器发送的参数

React this绑定的几点思考

以上是【js基础】变量类型判断的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
5个常见的JavaScript内存错误5个常见的JavaScript内存错误Aug 25, 2022 am 10:27 AM

JavaScript 不提供任何内存管理操作。相反,内存由 JavaScript VM 通过内存回收过程管理,该过程称为垃圾收集。

巧用CSS实现各种奇形怪状按钮(附代码)巧用CSS实现各种奇形怪状按钮(附代码)Jul 19, 2022 am 11:28 AM

本篇文章带大家看看怎么使用 CSS 轻松实现高频出现的各类奇形怪状按钮,希望对大家有所帮助!

Node.js 19正式发布,聊聊它的 6 大特性!Node.js 19正式发布,聊聊它的 6 大特性!Nov 16, 2022 pm 08:34 PM

Node 19已正式发布,下面本篇文章就来带大家详解了解一下Node.js 19的 6 大特性,希望对大家有所帮助!

实战:vscode中开发一个支持vue文件跳转到定义的插件实战:vscode中开发一个支持vue文件跳转到定义的插件Nov 16, 2022 pm 08:43 PM

vscode自身是支持vue文件组件跳转到定义的,但是支持的力度是非常弱的。我们在vue-cli的配置的下,可以写很多灵活的用法,这样可以提升我们的生产效率。但是正是这些灵活的写法,导致了vscode自身提供的功能无法支持跳转到文件定义。为了兼容这些灵活的写法,提高工作效率,所以写了一个vscode支持vue文件跳转到定义的插件。

浅析Vue3动态组件怎么进行异常处理浅析Vue3动态组件怎么进行异常处理Dec 02, 2022 pm 09:11 PM

Vue3动态组件怎么进行异常处理?下面本篇文章带大家聊聊Vue3 动态组件异常处理的方法,希望对大家有所帮助!

聊聊如何选择一个最好的Node.js Docker镜像?聊聊如何选择一个最好的Node.js Docker镜像?Dec 13, 2022 pm 08:00 PM

选择一个Node​的Docker镜像看起来像是一件小事,但是镜像的大小和潜在漏洞可能会对你的CI/CD流程和安全造成重大的影响。那我们如何选择一个最好Node.js Docker镜像呢?

聊聊Node.js中的 GC (垃圾回收)机制聊聊Node.js中的 GC (垃圾回收)机制Nov 29, 2022 pm 08:44 PM

Node.js 是如何做 GC (垃圾回收)的?下面本篇文章就来带大家了解一下。

【6大类】实用的前端处理文件的工具库,快来收藏吧!【6大类】实用的前端处理文件的工具库,快来收藏吧!Jul 15, 2022 pm 02:58 PM

本篇文章给大家整理和分享几个前端文件处理相关的实用工具库,共分成6大类一一介绍给大家,希望对大家有所帮助。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),