typeof 和 instanceof 想必各位前端小伙伴都不陌生,typeof只能检测基本数据类型,但是有个例外,检测基本类型null时返回的是"object",而typeof检测数组和对象时都是"object"。
console.log(typeof 12);
console.log(typeof "abc");
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof null);
console.log(typeof [1, 2, 3]);
console.log(typeof { a: 1 });
const fn = function () {};
console.log(typeof fn);
打印结果:
number
string
boolean
undefined
object
object
object
function
如果你想判断一个实例到底属于哪一个构造函数,instanceof是个不错的选择,
const arr = [1,2,3];
const obj = {a: 1};
function Person() {};
const p = new Person();
console.log(arr instanceof Array);
console.log(obj instanceof Object);
console.log(p instanceof Person);
但是instanceof有个缺陷,就是无法检测基本数据类型,那么有没有一个强大的方式可以对引用类型可基本类型都起作用,Object.prototype.toString这个方法可以完美的完成你想要的功能
console.log(Object.prototype.toString.call(12));
console.log(Object.prototype.toString.call("abc"));
console.log(Object.prototype.toString.call(true));
console.log(Object.prototype.toString.call(undefined));
console.log(Object.prototype.toString.call(null));
console.log(Object.prototype.toString.call([1, 2, 3]));
console.log(Object.prototype.toString.call({ a: 1 }));
const fn = function () {};
console.log(Object.prototype.toString.call(fn));
打印结果:
[object Number]
[object String]
[object Boolean]
[object Undefined]
[object Null]
[object Array]
[object Object]
[object Function]