一、typeof 运算符 (适用判断基础类型)
- 只能识别基础类型和引用类型
typeof 2; // => 'number'
typeof true; // => 'boolean'
typeof 'str'; // => 'string'
typeof []; // => 'object'
typeof {}; // => 'object'
typeof function a() {} // => 'function'
注意: null、NaN
console.log(typeof null); // object
console.log(typeof NaN); // number
不同的对象在底层都表示为二进制,在JavaScript中二进制前三位都为0的话会被判断为object类型,null 的二进制表示是全 0,自然前三位也是 0,所以执行 typeof 时会返回“object”,这是个历史遗留问题。
二、instanceof 运算符 (适用判断引用类型)
instanceof运算符适合于判断引用数据类型,对基本数据类型进行判断全返回false,无法判断,而对null、undefined不能使用instanceof运算符。
// 基础类型
2 instanceof Number; //=> false
true instanceof Boolean; //=> false
'str' instanceof String; //=> false
// 引用类型
{} instanceof Object; //=> true
[] instanceof Array; //=> true
new Date() instanceof Date; //=> true
new Error() instanceof Error; //=> true
new Set([1, 2, 3]) instanceof Set; //=> true
new Map([['name', 'Jack'],['age', 18]]) instanceof Map; //=> true
const fn = function (){}
fn instanceof Function; //=> true
三、constructor 属性
无法判断null、undefined,因为这两个没有constructor属性
(2).constructor === Number; //=> true
(true).constructor === Boolean; //=> true
('str').constructor === String; //=> true
(Symbol()).constructor === Symbol; //=> true
(BigInt('999446646455454')).constructor === BigInt; //=> true
(new Object).constructor === Object; //=> true
([]).constructor === Array; //=> true
(/^666/).constructor === RegExp; //=> true
(new Date()).constructor === Date; //=> true
(new Error()).constructor === Error; //=> true
(new Set([1, 2, 3])).constructor === Set; //=> true
(new Map([['name', 'Jack'],['age', 18]])).constructor === Map; //=> true
const fn = function (){}
(fn).constructor === Function; //=> true
四、函数借用:Object.prototype.toString.call(target)
对toString()方法进行函数借用可以对全部类型进行判断。
Object.prototype.toString.call(2); //=> '[object Number]'
Object.prototype.toString.call(true); //=> '[object Boolean]'
Object.prototype.toString.call('str'); //=> '[object String]'
Object.prototype.toString.call(Symbol()); //=> '[object Symbol]'
Object.prototype.toString.call(BigInt('999446646455454')); //=> '[object BigInt]'
Object.prototype.toString.call(null); //=> '[object Null]'
Object.prototype.toString.call(undefined); //=> '[object Undefined]'
Object.prototype.toString.call(new Object); //=> '[object Object]'
Object.prototype.toString.call([]); //=> '[object Array]'
Object.prototype.toString.call(/^666/); //=> '[object RegExp]'
Object.prototype.toString.call(new Date()); //=> '[object Date]'
Object.prototype.toString.call(new Error()); //=> '[object Error]'
Object.prototype.toString.call(new Set([1, 2, 3])); //=> '[object Set]'
Object.prototype.toString.call(new Map([['name', 'Jack'],['age', 18]])); //=> '[object Map]'
const fn = function (){}
Object.prototype.toString.call(fn); //=> '[object Function]'