zoukankan      html  css  js  c++  java
  • js类型判断-丰富加好用

    一,

    自己有时候写一些东西,要做类型判断,还有测试的时候,对于原生的和jQuery中的类型判断,实在不敢恭维,所以就写了一个好用的类型判断,一般情况都够用的。

     1 function test(type) {
     2                 if(type === null || type === undefined) {
     3                     return type;
     4                 }
     5                 // 如果是对象,就进里面判断,否则就是基本数据类型
     6                 else if (type instanceof Object) { // js对象判断, 由于typeof不能判断null object,所以只能提前判断,互相补充
     7                     if(type instanceof Function) {
     8                         return 'Function';
     9                     }else if(type instanceof Array) {
    10                         return 'Array';
    11                     } else if(type instanceof RegExp){
    12                         return 'RegExp';
    13                     }else if(type instanceof Date) {
    14                         return 'Date';
    15                     }
    16                     // 判断是节点对象还是JQuery对象,很有用,新手一般来说分不清什么是什么类型
    17                     else if(type instanceof Node){
    18                         return 'Node';
    19                     }else if(type instanceof jQuery){
    20                         return 'jQuery';
    21                     }
    22                     else{
    23                         return 'Object';
    24                     }
    25                 }
    26                 // 基本数据类型
    27                 else {
    28                     return typeof type;
    29                 }
    30             }
    View Code

    二,

    原生的代码限制很多,

    typeof只能判断基本数据类型外加undefied,Function。null会判断为object,Object和Array会判断为Object。

    instanceof 只能判断对象

    === 可以判断null,undefined。

    把上面三种方式组合起来,才能判断这些基本的类型。我有加入了另外几种类型判断,对于新手和老手,都是不错的工具。希望大家喜欢吧!

  • 相关阅读:
    初识 Mysql
    Python之协程
    crm 动态一级二级菜单
    admin 后台操作表格
    crm 权限设计
    crm 公户变私户的问题 班级管理 课程管理 学习记录初始化
    crm 添加用户 编辑用户 公户和私户的展示,公户和私户的转化
    crm 数据展示 和分页思想(一)
    python django(forms组件)
    python Django 中间件介绍
  • 原文地址:https://www.cnblogs.com/zanzg/p/9440647.html
Copyright © 2011-2022 走看看