1: typeof
对于字面量类型检测无误,但对于引用类型检测(如Array)不起作用
console.log("=========>>>", typeof ""); // =========>>> string
console.log("=========>>>", typeof 1); // =========>>> number
console.log("=========>>>", typeof true); // =========>>> boolean
console.log("=========>>>", typeof function(){}); // =========>>> function
console.log("=========>>>", typeof []); // =========>>> object ❌
console.log("=========>>>", typeof {}); // =========>>> object ❌
console.log("=========>>>", typeof null); // =========>>> object
console.log("=========>>>", typeof undefined); // =========>>> undefined
2:instanceof
从字面意思大概就可以猜测到,instance实例检测,是否是某构造函数的实例。
所以它对字面量的检测是无效的,对引用类型有效。
console.log("=========>>>", "" instanceof String); // =========>>> false ❌
console.log("=========>>>", 1 instanceof Number); // =========>>> false ❌
console.log("=========>>>", true instanceof Boolean); // =========>>> false ❌
console.log("=========>>>", [] instanceof Array); // =========>>> true
console.log("=========>>>", {} instanceof Object); // =========>>> true
console.log("=========>>>", function(){} instanceof Function); // =========>>> true
3:constructor
构造器,顾名思义,检测对象的构造器是什么类型;
对于字面量类型和引用类型它都能很好的检验出来
console.log("=========>>>", ("1").constructor=== String); // =========>>> true
console.log("=========>>>", (1).constructor=== Number); // =========>>> true
console.log("=========>>>", (true).constructor=== Boolean); // =========>>> true
console.log("=========>>>", ({}).constructor=== Object); // =========>>> true
console.log("=========>>>", ([]).constructor=== Array); // =========>>> true
console.log("=========>>>", (function(){}).constructor=== Function); // =========>>> true
4: Object.prototype.toString.call()
能检测出所有数据类型,包括null和undefined
console.log("====>>>", Object.prototype.toString.call("1")); // ====>>> [Object String]
console.log("====>>>", Object.prototype.toString.call(1)); // ====>>> [Object Number]
console.log("====>>>", Object.prototype.toString.call(true)); // ====>>> [Object Boolean]
console.log("====>>>", Object.prototype.toString.call({})); // ====>>> [Object Object]
console.log("====>>>", Object.prototype.toString.call(function(){})); // ====>>> [Object Function]
console.log("====>>>", Object.prototype.toString.call([])); // ====>>> [Object Array]
console.log("====>>>", Object.prototype.toString.call(null)); // ====>>> [Object Null]
console.log("====>>>", Object.prototype.toString.call(undefined)); // ====>>> [Object Undefined]
结论:
1:typeof 对字面量有效,对引用类型和null无效
2:instanceof 对引用类型有效,对字面量和null、undefined无效
3:constructor 对字面量和引用类型有效,对null、undefiend无效
4:Object.prototype.toString.call() 对所有数据类型检测有效 (✔️完美)












网友评论