JavaScript/typeof
来自康健生活
引言
- 内置类型的检测正确(null 为"object")。
- 方法进行检测,返回 function。
- 对象进行检测,返回 object。
| undefined | Undefined 类型 |
| boolean | Boolean 类型 |
| number | Number 类型 |
| string | String 类型 |
| symbol | Symbol 类型 |
| bigint | Bigint 类型 |
| function | Function 类型 |
| object | 引用类型或 Null 类型 |
实例
boolean
typeof true;
typeof false;
typeof (2 > 1);
'boolean'
string
typeof "str";
typeof "";
'string'
number
typeof 1;
typeof -1;
typeof 0;
typeof Math.PI;
typeof Infinity;
typeof NaN;
'number'
undefined
typeof undefined;
'undefined'
object
typeof [];
typeof {};
typeof new RegExp();
typeof new Date();
typeof new Error();
typeof new String();
typeof new Number();
typeof new Array();
typeof new Object();
typeof new Boolean();
typeof null;
'object'
typeof function(){};
typeof class C{};
typeof new Function();
typeof Number;
typeof Array;
'function'
symbol
typeof Symbol();
'symbol'
typeof 1n;
typeof BigInt("1");
'bigint'
null
类型检测
!null&&typeof null === "object"
true
原理
机器码低三位:
| 000 | 对象 | 示例 |
| 010 | 浮点数 | 示例 |
| 100 | 字符串 | 示例 |
| 110 | 布尔值 | 示例 |
| 1 | 整数 | 示例 |
| 000 | null | |
| undefined | -2^30 整数 |
undefined 和 null
undefined == null;
undefined === null;
Number(undefined);
Number(null);
true false NaN 0
es6
typeof new Set();
typeof new Map();
var foo = new Promise((resolve,reject)=>{});
typeof foo;
var bar = new Proxy({},{});
typeof bar;
"object" "object" "object" "object"
No categories