JavaScript判断数据类型的方法
- 利用运算符typeof或者typeof()方法
//基本类型console.log(typeof 1); //1console.log(typeof true); //booleanconsole.log(typeof undefined); //undefinedconsole.log(typeof 'string'); //stringconsole.log(typeof null); //objectconsole.log(typeof Symbol()); //symbolconsole.log(typeof 33n); //bigint//对象类型console.log(typeof []); //objectconsole.log(typeof function(){}); //functionconsole.log(typeof {}); //objectconsole.log(typeof new Set([1,2,3]));//objectconsole.log(typeof new Map([['o',1]]));//objectconsole.log(typeof p1); //object由此可以看出typeof运算符值对原始数据类型有用,对于对象数据类型就并没有那么准确
- instanceof运算符
console.log(1 instanceof Number); //false console.log('str' instanceof String); //false console.log([] instanceof Array); //true console.log([] instanceof Object); //true
首先,我们知道instanceof运算符是判断构造函数的prototype是否出现在实例的原型链上面,因此,此方法并不太适用判断数据类型
- constructor属性
//原始数据类型 console.log((1).constructor); //ƒ Number() { [native code] } console.log('str'.constructor); //ƒ String() { [native code] } console.log(true.constructor); //ƒ Boolean() { [native code] } console.log(null.constructor); // 报错 console.log(undefined.constructor); //报错 console.log((88n).constructor); //ƒ BigInt() { [native code] } console.log(Symbol().constructor); //ƒ Symbol() { [native code] } //对象数据类型 console.log([].constructor); //ƒ Array() { [native code] } console.log(function(){}.constructor); //ƒ Function() { [native code] } console.log({}.constructor); //ƒ Object() { [native code] } console.log(new Set([1,2,3]).constructor); //ƒ Set() { [native code] } console.log(new new Map([['o',1]]).constructor); //Map(0) {}
虽然看似很完美BUT。。。。
console.log(Number.prototype.constructor); //ƒ Number() { [native code] } console.log(String.prototype.constructor); //ƒ String() { [native code] }
由于constructor属性是定义在对象的原型上面,所以原型对象的constructor属性也直接指向构造函数
-
借用Object原型里的一个方法 :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(true)); //[object Boolean] console.log(Object.prototype.toString.call('str'));//[object String] console.log(Object.prototype.toString.call(11));//[object Number] console.log(Object.prototype.toString.call(function(){}));//[object Function] console.log(Object.prototype.toString.call([]));//[object Array] console.log(Object.prototype.toString.call({}));//[object Object] console.log(Object.prototype.toString.call(new Set([4,5,6]))); //[object Set]
此方法相对来说还是比较完美,但是要注意一定是从Object.prototype.toString用call方法借用才行