zoukankan      html  css  js  c++  java
  • ES6结合正则判断js数据类型

    ES5:(有重复,所以判断数组或对象等,就会有问题)

    typeof 1              ---> 'number'
    typeof 'hello'        ---> 'string'
    typeof alert          ---> 'function'
    typeof [1,2,3]       ---> 'object'
    typeof {a:1,b:2}   ---> 'object'
    typeof /d/            ---> 'object'
    typeof new Date()  ---> 'object'
    typeof null             ---> 'object'
    typeof NaN             ---> 'number'
    typeof undefined     ---> 'undefined'
    typeof Symbol()      ---> 'symbol'

    ES6: (修补了问题)

    console.log(Object.prototype.toString.call("hello"));//[object String]
    console.log(Object.prototype.toString.call(123));//[object Number]
    console.log(Object.prototype.toString.call(true));//[object Boolean]
    console.log(Object.prototype.toString.call(undefined));//[object Undefined]
    console.log(Object.prototype.toString.call(null));//[object Null]
    console.log(Object.prototype.toString.call({name: "jerry"}));//[object Object]
    console.log(Object.prototype.toString.call(function(){}));//[object Function]
    console.log(Object.prototype.toString.call([]));//[object Array]
    console.log(Object.prototype.toString.call(new Date));//[object Date]
    console.log(Object.prototype.toString.call(/d/));//[object RegExp]
    function foo(){}
    console.log(Object.prototype.toString.call(new foo()));//[object Object]

    最后ES6结合正则的方式,使用最方便:

    const isType = type =>(/^[objects(.*)]$/.exec(Object.prototype.toString.call(type)))[1];
    isType({}) // 'Object'
    isType([]) // 'Array'

    注意首字母是大写

    .

  • 相关阅读:
    解决问题:Jenkins Web 部署任务失败
    微信开发者调试工具官方下载地址
    Android机USB调试功能
    DOMContentLoaded 和 Load 和 Finish
    Json to string, string to Json
    static 和 new对象的区别
    c# Image/Pdf 预览
    在console 中执行异步方法
    c# 压缩zip
    js -- string 转 html
  • 原文地址:https://www.cnblogs.com/xiangsj/p/12971623.html
Copyright © 2011-2022 走看看