1.typeof方法判断数据类型,一般用于基本数据类型的判断,不适用引用数据类型,另外对于null,object、array返回的都是object,无法进行区分。
console.log(typeof null);//object
console.log(typeof {name:"小明"})//object
console.log(typeof [1,3,5,6]);//object
console.log(typeof undefined);//undefined
console.log(typeof 1);//number
console.log(typeof "1");//string
console.log(typeof Symbol);//function
console.log(typeof function(){});//function
console.log(typeof true);//boolean
2.instanceof方法 是用来 判断数据是否是某个对象的实例,返回一个布尔值。对于基本类型的数据,instanceof是不能直接判断它的类型的,因为实例是一个对象或函数创建的,是引用类型,所以需要通过基本类型对应的包装对象来判断。所以对于 null 和 undefined无法检测。
// 判断 p 是否为 Person 的实例
function Person(name) {
this.name = name
}
const p = new Person('sunshine')
console.log(p instanceof Person); // true
// 这里的 p 是 Person 函数构造出来的,所以顺着 p 的原型链可以找到Object的构造函数
console.log(p.__proto__ === Person.prototype); // true
console.log(p.__proto__.__proto__ === Object.prototype); // true
console.log(5 instanceof Number); // false
console.log(new Number(5) instanceof Number); // true
3.Object.prototype.toString.call()方法,这种方式判断数据类型是最准确的。
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call({name:"小明"}))//[object Object]
console.log(Object.prototype.toString.call([1,3,5,6]));//[object Array]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(1));//[object Number]
console.log(Object.prototype.toString.call("1"));//[object String]
console.log(Object.prototype.toString.call(Symbol));//[object Function]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call(true));//[object Boolean]