zoukankan      html  css  js  c++  java
  • js 检测数据类型的三种方式

    1、typeof

    typeof 用以获取一个变量或者表达式的类型,typeof 一般只能返回如下几个结果:

    typeof "John"                 // 返回 string
    typeof 3.14                   // 返回 number
    typeof NaN                    // 返回 number
    typeof false                  // 返回 boolean
    typeof [1,2,3,4]              // 返回 object
    typeof {name:'John', age:34}  // 返回 object
    typeof new Date()             // 返回 object
    typeof function () {}         // 返回 function
    typeof myCar                  // 返回 undefined (如果 myCar 没有声明)
    typeof null                   // 返回 object

    请注意:

    • NaN 的数据类型是 number
    • 数组(Array)的数据类型是 object
    • 日期(Date)的数据类型为 object
    • null 的数据类型是 object
    • 未定义变量的数据类型为 undefined

    如果对象是 JavaScript Array 或 JavaScript Date ,我们就无法通过 typeof 来判断他们的类型,因为都是 返回 object。

    我们可以使用 typeof 来获取一个变量是否存在,如 if(typeof a!="undefined"){},而不要去使用 if(a) 因为如果 a 不存在(未声明)则会出错。

    正因为 typeof 遇到 null,数组,对象时都会返回 object 类型,所以当我们要判断一个对象是否是数组时。

    或者判断某个变量是否是某个对象的实例则要选择使用另一个关键语法 instanceof。

    2、instanceof

    可通过 instanceof 操作符来判断对象的具体类型,语法格式:

    var result = objectName instanceof objectType

    返回布尔值,如果是指定类型返回 true,否则返回 false:

    例:

    arr = [1,2,3];
    if(arr instanceof Array){
        document.write("arr 是一个数组");
    } else {
        document.write("arr 不是一个数组");
    }

    3、constructor 属性

    constructor 属性返回所有 JavaScript 变量的构造函数。

    "John".constructor                 // 返回函数 String()  { [native code] }
    (3.14).constructor                 // 返回函数 Number()  { [native code] }
    false.constructor                  // 返回函数 Boolean() { [native code] }
    [1,2,3,4].constructor              // 返回函数 Array()   { [native code] }
    {name:'John', age:34}.constructor  // 返回函数 Object()  { [native code] }
    new Date().constructor             // 返回函数 Date()    { [native code] }
    function () {}.constructor         // 返回函数 Function(){ [native code] }

    你可以使用 constructor 属性来查看对象是否为数组 (包含字符串 "Array"):

    function isArray(myArray) {
        return myArray.constructor.toString().indexOf("Array") > -1;
    }

    你可以使用 constructor 属性来查看对象是否为日期 (包含字符串 "Date"):

    function isDate(myDate) {
        return myDate.constructor.toString().indexOf("Date") > -1;
    }
  • 相关阅读:
    PowerShell_零基础自学课程_7_Powershell中重定向机制、目录和文件管理
    volcanol_C语言学习趣事汇总贴
    linux_shell_2_shell 中的变量特性
    PowerShell_零基础自学课程_5_自定义PowerShell环境及Powershell中的基本概念
    volcanol_Linux_问题汇总系列_2_如何在linux和windows主机之间共享文件
    C语言学习趣事_你不知道的C语言应用
    volcanol_Windows_Powershell_汇总贴
    PowerShell_零基础自学课程_4_PowerShell的别名功能、错误管理功能和系统资源区域导航
    Sqlite 管理工具 SQLiteDeveloper及破解
    android建立Menu详解
  • 原文地址:https://www.cnblogs.com/art-poet/p/12098075.html
Copyright © 2011-2022 走看看