1、typeof
var arr =[1,2,3]
var obj ={name:"aaa"}
var fn = function(){
alert(1)
}
console.log(typeof(1)); //number
console.log(typeof("abc")); //string
console.log(typeof(true)); //boolean
console.log(typeof(undefined)); //undefined
console.log(typeof(null)); //object
console.log(typeof(arr)); //object
console.log(typeof(obj)); //object
console.log(typeof(fn)); //function
?由输出结果可以判断出:typeof类型无法判断null、object、Array的数据类型
2、instanceof
var arr =[1,2,3]
var obj ={name:"aaa"}
console.log(arr instanceof Array); //true
console.log(arr instanceof Object); //true
console.log(obj instanceof Object); //true
console.log(null instanceof Object); //false
?由此可见:instanceof可以判断出Array和object的数据类型,但是无法判断null的数据类型
3、===
var b = undefined
var c = null;
console.log(b === undefined); //true
console.log(c === null); //true
由此可见:===可以判断null和undefined的数据类型?
4、Object.prototype.toString(万能)
function typeOf(obj){
let res = Object.prototype.toString.call(obj).split(" ")[1];
res = res.substring(0,res.length-1)
console.log(res);
}
let fn = function(){
alert(1)
}
typeOf(1) //Number
typeOf(true) //Boolean
typeOf([]) //Array
typeOf({}) //Object
typeOf(null) //Null
typeOf(new Date) //Date
typeOf("123") //String
typeOf(undefined) //Undefined
typeOf(fn) //Function
Object.prototype.toString.call()使用此方法,会先返回一个结果即Object,
若call内有参数,则返回的是他的数据类型,如果没有参数,最后返回的是undefined
这种方法可以方便的判断出所有的数据类型
|