类型判断
typeof
typeof判断除null
之外的基本类型(原始类型)。
console.log(typeof undefined);//undefined
console.log(typeof 1);//number
console.log(typeof '1');//string
console.log(typeof true);//boolean
console.log(typeof Symbol('1'));//symbol
console.log(typeof BigInt(1));//bigint
typeof判断引用类型(对象类型),除了函数是function外,其他都是object,不能判断具体的类型。
instanceof
instanceof通过原型链来判断是否是构造函数的实例。
var obj = new Object();
var map = new Map();
var arr = new Array();
var set = new Set();
var str = new String();
function fun(){}
console.log(obj instanceof Object);//true
console.log(map instanceof Map);//true
console.log(arr instanceof Array);//true
console.log(set instanceof Set);//true
console.log(str instanceof String);//true
console.log(fun instanceof Function);//true
构造函数
var obj = new Object();
var map = new Map();
var arr = new Array();
var set = new Set();
var str = new String();
function fun(){}
console.log(obj.constructor === Object);//true
console.log(map.constructor === Map);//true
console.log(arr.constructor === Array);//true
console.log(set.constructor === Set);//true
console.log(str.constructor === String);//true
console.log(fun.constructor === Function);//true
Object.prototype.toString.call
Object.prototype.toString.call可以判断基本类型和引用类型。
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(1));//[object Number]
console.log(Object.prototype.toString.call('1'));//[object String]
console.log(Object.prototype.toString.call(1n));//[object BigInt]
console.log(Object.prototype.toString.call(Symbol('1')));//[object Symbol]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(new Array()));//[object Array]
console.log(Object.prototype.toString.call(new Object()));//[object Object]
console.log(Object.prototype.toString.call(new Map()));//[object Map]
console.log(Object.prototype.toString.call(new Set()));//[object Set]
console.log(Object.prototype.toString.call(function fn(){}));//[object Function]
isXXX API
console.log(Array.isArray([]));//true
console.log(isNaN('fdfd'));//true