1.typeof:能判断所有值类型,函数,不能判断、数组、对象进行精确判断;
console.log(typeof undefined); // undefined
console.log(typeof true); // boolean
console.log(typeof 2); // number
console.log(typeof "string"); // string
console.log(typeof Symbol("foo")); // symbol
console.log(typeof 2172141653n); // bigint
console.log(typeof function () {}); // function
// 不能判别
console.log(typeof []); // object
console.log(typeof {}); // object
console.log(typeof null); // object
2.instanceof :判断对象类型,不能判断基本数据类型,内部运行机制是在其原型链上能否找到该类型的原型;
class Person {}
class Student extends Person
const obj = new Student
console.log(obj instanceof Person) //true
console.log(obj instanceof Student ) //true
//obj 顺着原型链能找到Student.prototype和Person.prototype,所以都为true
3.Object.prototype.toString.call():所有原始数据类型都能判断;
Object.prototype.toString.call(2) //"[object Number]"
Object.prototype.toString.call('') // "[object String]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(Math); // "[object Math]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(function () {}); // "[object Function]"