一.typeof
二.instanceof
三.通过Object.prototype.toString
一.typeof
语法: typeof 需要判断的数据类型
console.log(typeof 123); //number
console.log(typeof '王小美'); //string
console.log(typeof true); //boolean
console.log(typeof undefined); //undefined
console.log(typeof null); //object
console.log(typeof [123, 4]); //object
console.log(typeof function () { }); //function
console.log(typeof { name: '王小美' }); //object
可以看出判断的基本上是没有什么太大问题的,但是判断null时返回的却是object
所以这是typeof的缺点还是优点呢?说缺点的话这个null归类于object确实有点不合适
说优点的话只有typeof判断null的时候返回的是object哈哈哈哈
判断数组的时候返回的也是object,但数组是Array
二.instanceof
语法: 对象 instanceOf 构造函数名
作用: 判断这个复杂数据类型的prototype在不在这个对象的原型链上
返回布尔值
let arr = [10, 20, 30];
let str = {}
let str2 = '王小美';
let fn = function () { }
console.log(arr instanceof Array); //true
console.log(arr instanceof Object); //true
console.log(fn instanceof Function); //true
console.log(fn instanceof Object); //true
console.log(str instanceof Object); //true
console.log(str instanceof Function); //false
console.log(str2 instanceof String); //返回false 判断不出来
// 根据原型链去查找 根据instanceof的语法来判断的话前面的Object会被看成对象
// 结果都为true
console.log(Object instanceof Object);
console.log(Object instanceof Function);
// 都为true
console.log(Function instanceof Function);
console.log(Function instanceof Object);
三.通过Object.prototype.toString
万能数据监测[object type]type是数据类型
let str = { name: '王小美' }
//对象调用toString()方法时返回[object type];其他数据类型调用toString时会返回其他内容
console.log(str.toString()); //[object Object]
这个方法是在Object原型上的方法,如果要使用的话就要改变这个方法的this指向,借用一下,具体就是让这个方法指向我们输入的数据类型
// call()和apply,bind方法都可以
console.log(Object.prototype.toString.call(123)); // [object Number]
console.log(Object.prototype.toString.call('abc')); // [object String]
console.log(Object.prototype.toString.call(true)); // [object Boolean]
console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
console.log(Object.prototype.toString.call(null)); // [object Null]
console.log(Object.prototype.toString.call([123, 4])) // [object Array]
console.log(Object.prototype.toString.apply([123, 4])) // [object Array]
console.log(Object.prototype.toString.call(function () { })) // [object Function]
console.log(Object.prototype.toString.call({ name: '王小美' })) // [object Object]
结果在右边,底部有滚动条
上面就是我所知的一些判断数据类型的方法 ,如果有其他方法可以评论哈,或者发现我有错误的话谢谢指出哈