【最全】判断数据类型的方法,其优缺点以及返回值

判断数据类型的方法,其优缺点以及返回值

一、typeof(都是小写)

优点:typeof是操作符,可以判断基本数据类型(返回值有:undefined,number,string,boolean,object,function)                      

缺点:不能判断出null,object,Array,因为它们的返回值都是object,Array属于object。typeof判断是由他们前三位的二进制决定的,null由于它的二进制都是0,object的前三位为0,所以typeof判断出它们都是object。

let a1=[1,23,3];
let a2=5;
let a3=true;
let a4="haha";
let a5=null;
let a6=undefined;
let a7=function dd(){};
let a8={
    name:'zs',
    age:12
}
console.log(typeof(a2));    //number
console.log(typeof(a3));    //boolean
console.log(typeof(a4));    //string
console.log(typeof(a6));    //undefined
console.log(typeof(a5));    //object
console.log(typeof(a1));    //object
console.log(typeof(a7));    //function
console.log(typeof(a8));    //object

二、instanceof

多用于检测应用数据类型,表达方式:a instanceof b   (a是否是b的实例)返回值为true,false

注:null,undefined不属于object。


let arr=[1,23,3];
console.log(arr instanceof Array);  //true
console.log(null instanceof Object);    //false
console.log(undefined instanceof Object);   //false

三、constructor

function Person(){
    let c;
};
let person=new Person();
let a=1;
console.log(person.constructor==Person);    //true
console.log(a.constructor==Number);         //true
console.log(a.constructor);                 //[Function: Number]
console.log(a.constructor.name);            //Number

四、Object.prototype.toString.call()

优点:相对来说可以很好的区分数据类型,它可以区分 null 、 string 、boolean 、 number 、 undefined 、 array 、 function 、 object 、 date 、 math 数据类型。

缺点:代码优点长。

console.log(Object.prototype.toString.call(1));     //[object Number]
console.log(Object.prototype.toString.call(null));      //[object Null]
console.log(Object.prototype.toString.call(undefined));     //[object Undefined]
console.log(Object.prototype.toString.call(function b(){}));    //[object Function]
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值