关于JavaScript的那些数据类型

109 阅读1分钟

JavaScript的基本类型有哪些

数据类型
  • 值类型:Number; String; Boolean; null; undefined

  • 引用类型:Function; Object; Array

区别
  • undefined:表示变量声明但未初始化得值

  • null:表示准备用来保存对象,还没有真正保存对象的值,从逻辑角度看,null值表示一个空对象指针

  1. ECMA标准要求null和undefined等值判断返回值true
  • null==undefined//true

  • null===undefined//false

如何判断JavaScript的数据类型

判断方法

typeof

  • typeof可以用来区分除了null类型以外的原始数据类型,对象类型都可以从普通对象里面识别出函数

  • typeof undefined // "undefined"

  • typeof null // "object"

  • typeof 1 // "number"

  • typeof "1" // "string"

  • typeof Array // " object"

  • typeof function() {} // "function"

  • typeof { } // "object"

  • typeof true//"boolean"

typeof 数据检测类型

Snipaste_2022-04-28_22-24-35.png

  1. typeof不能识别null,如何识别null?
  • 可以直接使用===全等运算符来判断(或Object.prototype.toString)
  1. typeof作用未定义的变量,会报错吗
  • 不会报错会返回undefined
  1. 数据类型判断Object.prototype.toString
  • Object.prototype.toString.call(undefined)// "Undefined"

  • Object.prototype.toString.call(null) // "Null"

  • Object.prototype.toString.call(3)// "Number"

  • Object.prototype.toString.call(true) // "Boolean"

  • Object.prototype.toString.call('3') // "String"

  • Object.prototype.toString.call([]) // "Array"

  • Object.prototype.toString.call({})// "Object"

  • Object.prototype.toString.call(function(){})// "Function"

数据类型判断Object.prototype.toString

Snipaste_2022-04-28_22-25-30.png

付出,就不要后悔;失去,也不要遗憾。没有一个人,一生没有坎坷;没有一个人,一世没有痛苦。看你的人多,懂你的人少;说你的人多,帮你的人少。理解你的人,毕竟少而又少;帮助你的人,毕竟微乎其微。