JS判断数据的“类型”最稳定的、没局限的方式:Object.prototype.toString.call()

JS有三种判断数据类型的方法:

  • typeof
  • instanceof
  • Object.prototype.toString.call()

但是前面两种方法是有局限性的,它们能判断的数据类型只适用某些数据。详细的不再多说,想继续学习typeof、instanceof的作用范围和原理,可以看我这篇博客。

下面就说说判断数据的“类型”最稳定、全面的方式:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Object.prototype.toString</title>
  </head>
  <body>
    <script>
      function _typeof(data) {
     
     
        let reg = /\[object (\w+)\]/ //匹配toString()返回的值的正则表达式
        let ary = reg.exec(Object.prototype.toString.call(data))
        return ary ? ary[1].toLowerCase() : ''
      }

      function test() {
     
     
        let obj = null
        console.log(_typeof(obj) === 'null')

        obj = undefined
        console.log(_typeof(obj) === 'undefined')

        obj = '我是字符串'
        console.log(_typeof(obj) === 'string')

        obj = 111
        console.log(_typeof(obj) === 'number')

        obj = {
     
     
          name: '鸭绒',
        }
        console.log(_typeof(obj) === 'object')

        obj = [1, 2, 3]
        console.log(_typeof(obj) === 'array')

        obj = function () {
     
     
          console.log(1)
        }
        console.log(_typeof(obj) === 'function')
      }
      test()
    </script>
  </body>
</html>

在这里插入图片描述

分析:

首先需要知道Object.prototype.toString.call(data)它是会一个字符串,格式为'[object type]', type 即为该变量的数据类型:Number、String、Null、Undefined、Boolean、Object、Function、Array。

我们经常看到的是直接使用Object.prototype.toString.call(obj)==='[object Object]',假设obj就是一个对象变量,那么这个条件就是true,这也是可以的。在这里我复杂一点,直接将toString()的返回值[object type]中的type利用正则表达式将它提取出来,将type转化为小写,再判断数据类型。

猜你喜欢

转载自blog.csdn.net/weixin_43334673/article/details/110918679