JS 中分为七种内置类型,七种内置类型又分为两大类型:基本类型和对象(Object)。
基本的类型有六种: null
,undefined
,boolean
,number
,string
,symbol
。
其中 JS 的数字类型是浮点类型的,没有整型。并且浮点类型基于 IEEE 754标准实现,在使用中会遇到某些 Bug。详情请见此处(0.1+0.2==0.3 TODO)。
对于基本类型来说,如果使用字面量的方式,那么这个变量只是个字面量,只有在必要的时候才会转换为对应的类型
let a = 111 // 这只是字面量,不是 number 类型
a.toString() // 使用时候才会转换类型
对象(Object)是引用类型,在使用过程中会遇到浅拷贝和深拷贝的问题(TODO)。
let a = { name: 'FE' }
let b = a
b.name = 'EF'
console.log(a) // EF
typeof
对于基本类型,除了 null
都可以显示正确的类型
typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof b // b 没有声明,但是还会显示 undefined
typeof
对于对象,除了函数都会显示 object
typeof [] // 'object'
typeof {} // 'object'
typeof console.log // 'function'
对于 null
来说,虽然它是基本类型,但是会显示 object
,这是一个存在很久了的 Bug
typeof null // 'object'
PS:为什么会出现这种情况呢?因为在 JS 中二进制前三位都为0的话会被判定为 object
类型,null
的二进制都为0,所以被判定为 object
。