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'

    注意首字母是大写

    .

  • 相关阅读:
    laravel框架简易对接网易163邮件
    新版PHP7安装redis扩展并在laravel中运用
    make: as86: Command not found
    Ubuntu主题美化
    Ubuntu更换阿里源
    Ubuntu配置中文输入法
    JS内利用Ajax同后端异步交互数据
    更改网页内滚动条效果
    鼠标点击烟花特效
    内存交换分区创建&文件系统观察与操作
  • 原文地址:https://www.cnblogs.com/xiangsj/p/12971623.html
Copyright © 2011-2022 走看看