JavaScript 有哪些数据类型?如何判断一个变量的类型?
JavaScript 共有 8 种数据类型,分为两大类:
原始类型(7种)
number— 数字string— 字符串boolean— 布尔值undefined— 未定义null— 空值symbol— 唯一值(ES6)bigint— 大整数(ES2020)
引用类型(1种)
object— 对象(包括 Array、Function、Date、RegExp 等)
类型判断方法
| 方法 | 说明 | 缺点 |
|---|---|---|
typeof |
判断原始类型 | typeof null === 'object',无法区分数组/对象 |
instanceof |
判断引用类型 | 不能跨 iframe,不能判断原始类型 |
Object.prototype.toString.call() |
最准确 | 写法繁琐 |
Array.isArray() |
判断数组 | 仅用于数组 |
typeof 'hello' // 'string'
typeof 123 // 'number'
typeof null // 'object' ⚠️ 历史遗留 bug
typeof [] // 'object'
typeof function(){} // 'function'
[] instanceof Array // true
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call([1,2]) // '[object Array]'
Object.prototype.toString.call(new Date()) // '[object Date]'面试技巧:万能类型判断封装:
Object.prototype.toString.call(val).slice(8, -1)