《javascript代码优化指南》
参考笔记
数据类型
13.1 类型检测
javaScript中数据类型,可以分为 值类型、枚举类型、null、undefined
。
- 值类型可以通过typeof进行判断
- 枚举类型则可以通过 instanceof
- 而null、undefined则可以直接通过null进行判断
示例:
值类型通过typeof直接进行检测
// string
typeof variable -->'string'
// number
typeof variable --> 'number'
// boolean
typeof variable --> 'boolean'
// Function
typeof variable --> 'function'
枚举类型,通过以下方法是无法进行判断的
//null
typeof variable --> 'object'
// object
typeof variable --> 'object'
// Date
typeof variable --> 'object'
对于枚举类型就要采用instanceof进行判断
// RegExp
variable instanceof RegExp --> true
// Array
variable instanceof Array --> true
而 undefined 或 null 则统一采用 undefined进行判断。
// null or undefined
variable == null --> true
13.2 类型判断
总是使用 === 精确的比较操作符,避免在判断的过程中,由 JavaScript 的强制类型转换所造成的困扰。
如果你使用 === 操作符ÿ