数据类型
基本数据类型:
- Number
- String
- Boolen
- undefined
- null
- BigInt
- Symbol
引用类型:
- Object(Array/Function)
类型判断
类型判断常用方法:typeof instanceof Object.prototype.toString
typeof
用法
const a = '1';
typeof a === 'string' // true
typeof [1] // 'object'
原理
js在底层存储变量的时候,会在变量的机器码的低位1-3位存储其类型信息,typeof通过机器码确定类型。
- 对象: 000
- 浮点数: 010
- 字符串: 100
- 布尔: 110
- 整数: 1
- null: 00000000000...(所有机器码低位1-3位均为0)
- undefined:用 −2^30 整数来表示
| 类型 | 结果 |
|---|---|
| Undefined | "undefined" |
| Null | "object" (null机器码跟object) |
| Boolean | "boolean" |
| Number | "number" |
| BigInt(ECMAScript 2020 新增) | "bigint" |
| String | "string" |
| Symbol (ECMAScript 2015 新增) | "symbol" |
| 宿主对象(由 JS 环境提供 | 取决于具体实现 |
| Function 对象 (按照 ECMA-262 规范实现 [[Call]]) | "function" |
| NaN | 'number' |
instanceof
用法
const a = '1';
a instanceof String // true
原理
左边变量的原型链上(proto)查找到 右边变量(构造函数)的原型 (String.prototype)。
放一个例子
leftValue = Object.__proto__ = Function.prototype;
rightValue = Object.prototype;
// 第一次判断
leftValue != rightValue
leftValue = Function.prototype.__proto__ = Object.prototype
// 第二次判断
leftValue === rightValue
// 返回 true
Object.prototype.toString
更加稳妥的判断方式
Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call('string') // "[object String]"
Object.prototype.toString.call({a:'hi'}) // "[object Object]"
Object.prototype.toString.call([1]) // "[object Array]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(() => {}) // "[object Function]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(Symbol(1)) // "[object Symbol]"
面试题
判断数组的方法?
方法1:
Object.prototype.toString.call([1]) // "[object Array]"
方法2:
Array.isArray([]) // true
方法3:
[1] instanceof Array // true