众所周知,js有7种数据类型

  1. null

  2. undefined

  3. boolean

  4. number

  5. string  

  6. 引用类型(object、array、function)

  7. symbol

判断类型有以下4种判读方法

第一种方式: typeof

  typeof null ---> "object"

  typeof undefined ---> "undefined"

  typeof true | false ---> 'boolean'

  typeof 42 ---> 'number'

  typeof "42" ---> 'string'

  typeof { name : '1'} | [] ---> 'object'

  typeof Symbol ---> 'symbol'

  typeof ()=>{} ---> 'function'

  typeif void 0 ---> 'undefined'

第二种方式 instanceof 但是这种方式只适合判断object类型

  比如 : var arr = [] ; arr instanceof Array ---> true

      null instanceof Object ---> false

     [function] instanceof Object | Function --> true

第三种方式 Object.prototype.toString.call() 这种方式可以将全部的数据类型检测出来 也是 推荐的方式

  因为toString是Object的原型方法, 而 Array Function 等都是Object的实例。都重写了toString 方法。返回的是类型的字符串

  Object.prototype.toString.call(null) ---> [object Null]

  Object.prototupe.toString.call(undefined) ---> [object Undefined]

  Object.prototype.toString.call(123) ---> [object Number]

  Object.prototype.toString.call(true) ---> [object Boolean]

  Object.prototype.toString.call('123') ---> [object String]

  Object.prototype.toString.call({}) ---> [object Object]

  Object.prototype.toString.call([]) ---> [object Array]

  Object.prototype.toString.call(Math) ---> [object Math]

  Object.prototype.toString.call(function(){}) ---> [object Function]

  Objdec.prototype.toString.call(new Date) ---> [object Date]

  Object.prototype.toString.call(Symbol()) ---> [object Symbol]

第四种方式: constructor 判断对象的构造函。

  1. null 是js 原型链的起点,没有构造函数

  2. undefined 没有构造函数

  3. [].constructor === Array ---> true

  4. [string].constructor === String

  5. [object].constructor === object

  6. [number].constructor === Number

  7. [symbol].constructor === Symbol

  8. [function].constructor === Function

  9. [new Date].constructor === Date

  10. [RegExp].constructor === RegExp

来源 https://www.cnblogs.com/amiezhang/p/10325558.html

最新文章

  1. 【JAVA】 UIMnager
  2. easyui datagrid加载json
  3. python基础——枚举类
  4. Linux SO_KEEPALIVE属性,心跳
  5. Linux上在同一端口上共享SSH与HTTPS的工具:SSLH
  6. spring boot 配置文件提示自定义配置属性
  7. 【转】vlc android 代码编译
  8. wpf的datagrid和winform的datagridview刷新
  9. fatal error RC1004: unexpected end of file found处理方法
  10. Java WEB工程搭建UEditor
  11. iOS监听模式系列之iOS开发证书、秘钥
  12. TensorFlow tutorial
  13. rpc概念及nfs的基本应用
  14. Git推送错误Remote: User permission denied错误解决方法
  15. python接口测试—post请求(二)
  16. js 处理 cookie的存储与删除
  17. JavaScript快速入门-ECMAScript对象介绍
  18. 更换mysql数据库的datadir目录
  19. Python实现Json结构对比的小工具兼谈编程求解问题
  20. spring自定义注解拦截器的配置

热门文章

  1. maven依赖总结
  2. clion 查看代码 多次查看后如何一步一步回退到最初查看的代码位置
  3. IDEA将指定package(指定文件)打成jar包
  4. [转]使用 curl 发送 POST 请求的几种方式
  5. jdk1.7 64位官方下载
  6. (转载)CNN 模型所需的计算力(FLOPs)和参数(parameters)数量计算
  7. Python 安装 MySQL-python ImportError: No module named 'ConfigParser'
  8. Consul ACL集群配置说明以及ACL Token的用法
  9. 手贱重置了mysql密码,导致登陆不进去的解决办法
  10. spring跨重定向传递数据