检测数据类型的三种方法

1,235 阅读1分钟

一.基本数据类型

  1. number===>数字类型
  2. string===>字符串类型
  3. boolean===>布尔类型
  4. undefined===>未定义类型
  5. null===>空类型

二.引用数据类型

  1. Array===>数组类型
  2. Object===>对象类型
  3. function===>函数类型

三.typeof方法检测数据类型

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>

<body>
  <script>
    /*
    对变量或值调用 typeof 运算符将返回下列值之一:

  undefined - 如果变量是 Undefined 类型的 
  boolean - 如果变量是 Boolean 类型的 
  number - 如果变量是 Number 类型的 
  string - 如果变量是 String 类型的 
  object - 如果变量是一种引用类型或 Null 类型的 
  注释:您也许会问,为什么 typeof 运算符对于 null 值会返回 "Object"。
  这实际上是 JavaScript 最初实现中的一个错误,然后被 ECMAScript 沿用了。
  现在,null 被认为是对象的占位符,从而解释了这一矛盾,但从技术上来说,它仍然是原始值。
    */
    console.log(typeof 18) // number
    console.log(typeof 'ls') // string
    console.log(typeof true) // boolean
    let age
    console.log(typeof age) // undefined
    let a = null
    console.log(typeof a)//object
    console.log(typeof undefined)// undefined
    console.log(typeof null)//object
    console.log(typeof [1, 2, 3])//object
    console.log(typeof {})//object
    console.log(typeof function () { })//function
  </script>
</body>

</html>

  • 关于typeof的一些细节:
    返回的结果都是字符串,还有对于null和数组的检测结果也为object

四.instanceof方法检测数据类型

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        /* 
        1. instanceof(关键字): 运算符。用于检测 构造函数的prototype在不在实例对象的原型链中
            简单来说: 亲子鉴定,鉴定两个对象之间有没有血缘关系
        2.  实例对象 instanceof 构造函数
            检测 右边构造函数的prototype 在不在 左边实例对象的原型链中
        
        3. 应用 :  某些函数为了限制你的数据类型,
        在内部需要用instanceof进行判断是否是正确的数据类型
        */    

        let arr = [10,20,30]
        // arr-> Array.prototype -> Object.prototype -> null
        console.log( arr instanceof Array )//true
        console.log( arr instanceof Object )//true
        console.log( arr instanceof String )//false

        //封装一个函数,要求这个函数必须要传数组类型、 传其他类型不可以
        function fn(arr){
            if( arr instanceof Array){
                console.log( arr.reverse() )
            }else{
                console.log('数据类型错误')
            }
        }

        fn( [10,20,30] )//[30,20,10]
        fn( 'abc' )//数据类型错误
        
    </script>
</body>
</html>

instanceof方法检测数据类型注意点:

  • 返回一个boolean数据,来判断是否属于该类数据
  • 原理就是通过原型链来判断实例的__proto__是否与检测类型的prototype一致
  • instanceof无法检测基本数据类型,比如一个number、string等,除非是类的实例

五. 使用Object的toString方法来判断

  • 使用时Object.prototype.toString.call(需要判断的值),返回的是"[object,*******]"
  • 通过call来改变Object的toString方法的this指向,从而达到判断类型的效果