参考文章:JavaScript中判断对象类型的几种方法总结
1、原始数据类型
6种:number、string、boolean、undefined、null、symbol
一、typeof
let str = 'hello';
console.log(typeof str); // string
2、对于部分引用数据类型:object、function,也可以使用typeof
let obj = {}
console.log(typeof obj); // object
function func(){
return 'this is a function';
}
console.log(typeof func); // function
3、对于其他的引用数据类型:Array、Date、RegExp
二、instanceof
let arr = [1,2,3,4];
console.log(arr instanceof Array); // true
三、constructor属性
let arr = [1,2,3,4];
console.log(arr.constructor); // ƒ Array() { [native code] },引用了初始化该对象的构造函数
console.log(arr.constructor === Array); // true
补充:到底什么是JS原型
4、对于跨框架
四、Object.prototype.toString()
参考:JavaScript 中 call()、apply()、bind() 的用法
let arr = [1,2,3,4];
console.log(Object.prototype.toString.call(arr)); // [object Array]
console.log(Object.prototype.toString.call(arr) === "[object Array]");
console.log(Object.prototype.toString.apply(arr));
console.log(Object.prototype.toString.apply(arr) === "[object Array]");
console.log(Object.prototype.toString.bind(arr)); // ƒ toString() { [native code] }
console.log(Object.prototype.toString.bind(arr)()); //[object Array]
console.log(Object.prototype.toString.bind(arr)() === "[object Array]");