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。

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

  • 相关阅读:
    python面向对象(一)
    ls和cd命令详解
    SHELL 中的变量
    Shell基础
    Python版飞机大战
    Python模块制作
    Linux的cut命令
    Linux中的wc命令
    Ubuntu系统下adb devices 不能显示手机设备
    app耗电量测试工具--PowerTutor
  • 原文地址:https://www.cnblogs.com/zanzg/p/9440647.html
Copyright © 2011-2022 走看看