✨总结:
- 使用
typeof判断基本类型 (除了 null, null 用===来判判断) ,使用instanceof来判断引用类型- 或者使用
Object.prototype.toString.call(任何类型都能测)直接速通类型检测 😎
JS 中的基本类型(七种):
- boolean
- null
- undefined
- number
- string
- symbol
- bigint
JS 中的引用类型(记住下面这些即可):
- 普通对象-Object
- 数组对象-Array
- 正则对象-RegExp
- 日期对象-Date
- 数学函数-Math
- 函数对象-Function
类型转换方法 1: typeof
在 JavaScript 中, typeof 运算符用于检测变量的类型。
typeof 检测基本类型:
- boolean
let boolVar = true
console.log(typeof boolVar) // 输出 "boolean"
- null
let nullVar = null
console.log(typeof nullVar) // 输出 "object" (注意:这是JavaScript的一个历史遗留问题, `typeof null` 返回 "object") ,如果想要判断`null`,我们可以使用`===`来判断
- undefined
let undefVar
console.log(typeof undefVar) // 输出 "undefined"
- number
let numVar = 123
console.log(typeof numVar) // 输出 "number"
- string
let strVar = 'Hello, World!'
console.log(typeof strVar) // 输出 "string"
- symbol (ES6 引入的新类型)
let symbolVar = Symbol('unique')
console.log(typeof symbolVar) // 输出 "symbol"
- bigint (ES10 引入的新类型)
let bigIntVar = 12345678901234567890n // n 后缀表示这是一个 BigInt 类型的字面量
console.log(typeof bigIntVar) // 输出 "bigint"
typeof 检测引用类型:
除了函数对象 Function 之外,其他都返回 Object 。这也是 typeof 的一个缺点。
// 函数对象
const func = () => {
console.log('hello')
}
console.log(typeof func) // function
// 其他对象
let obj1 = {}
console.log(typeof obj1) // object
let obj2 = []
console.log(typeof obj2) // object
let obj3 = new Date()
console.log(typeof obj3) // object
类型转换方法 1: instanceof✨ instanceof 运算符会沿着待测内容的原型链查找, 看它是否能在某个地方找到给定的构造函数。如果能找到, 那么 instanceof 就返回 true, 否则返回 false。
[] instanceof Array// true
[] instanceof Object// true 数组的原型链上能找到Array,也能找到Object
const j = new Jiang()
j instanceof Jiang// true
Jiang instanceof Jiang// false: 自己不在自己的原型链上,所以返回false
再次总结:
- 使用
typeof判断基本类型,除了 null, null 使用===。使用instanceof来判断引用类型,instanceof基于原型链。- 使用
Object.prototype.toString.call(任何类型都能测)直接速通类型检测