zoukankan      html  css  js  c++  java
  • javascript数据类型检测方法

    一、字符串、数字、布尔值、undefined的最佳选择市使用 typeof 运算符进行检测:

    • 对于字符串,typeof 返回"string"
    • 对于数字,typeof 返回"number"
    • 对于布尔值,typeof 返回"boolean"
    • 对于undefined,typeof 返回"undefined"

    用法:typoef variable 或 typeof(variable)

    二、null 判断

      由于 typeof null 返回的值为 "object"(这是一个被诟病的语言本身设计存在的BUG),我们不能使用 typeof 来对 一个变量值是否为 null 进行判断。此外我们一般不建议将变量与 null 进行比较。

    不好的写法:

    if( item !== null ) {
      // 执行一些逻辑......
    }
    

    除非在你能预见该变量有可能等于 null 的情况下,你才可以使用恒等运算符(===)和非恒等运算符(!==)进行比较:

    var ele = document,getElementById("box");
    if( ele === null ) { // 执行一些逻辑...... }

    三、数组、对象与函数的检测

    1. 数组,由于数组属于引用类型,并且使用 typeof 对其进行检测返回的值为"object",在无法使用 typeof 判断的情况下,最佳的解决方案如下:

    function isArray( value ) {
        if( typeof Array.isArray === "function" ) {
            return Array.isArray(value);
        } else {
            return Object.prototype.toString.call(value)  ===  "[object Array]";
        }
    }
    

    2. 函数,虽然函数也属于引用类型,但因为 typeof 对函数检测的返回值为"function",因此检测函数的最好方案是使用 typeof :

    function func() {}
    
    typeof func === "function" // true
    

    陷阱:在 IE8 及 IE8 以下中使用 typeof 对DOM 节点中的方法检测会返回"object",因此在该场景下的替换方案为:

    // IE8及IE8以下
    console.log( typeof document.getElementById ); // "object"
    
    // 替换方案
    if( "getElementById" in document ) {
        //执行逻辑......
    }

    3. 自定义对象和内置对象,由于 typeof 对所有引用类型数据都返回"object"(函数除外),因此我们一般使用 instanceof 来判断其属于哪种引用类型:

    (跨frame使用会出现问题,因为每个文档都有各自的内置对象Object、Date、Function等)

    var obj = {}
    console.log( obj instanceof Object ); // true
    
    function Person (name) {
        this.name = name
    }
    
    var person = new Person("Jack");
    console.log( person instanceof Person ); // true
    
    var time = new Date();
    console.log( time instanceof Date ); // true
    

     

  • 相关阅读:
    python 获取在线视频时长,不下载视频
    python treeview 多线程下表格插入速度慢解决方法
    c#操作magick,magick.net
    油猴脚本-Tampermonkey-淘宝dsr过滤器(过滤非3红商品)
    python 基础小坑 0==False is True
    pyd 编译,简单命令cythonize
    python 调用Tesseract,dll模式,无需安装,绿色版
    list与set的查询效率,大量数据查询匹配,必须选set
    selenium 页面加载慢,超时的解决方案
    selenium 不打印chromedriver的日志信息
  • 原文地址:https://www.cnblogs.com/WhiteCusp/p/3679311.html
Copyright © 2011-2022 走看看