JavaScript之如何判断数据类型的几种方法

判断数据类型的方法有以下几种:

1.typeof:  返回的是string类型

    判断基本数据类型:string、number、boolean、function、undefined类型

    举例:

console.log(typeof('str'));            //string
console.log(typeof(123));              //number
console.log(typeof(true));             //boolean
console.log(typeof(function(){}));     //function
console.log(typeof(undefined));        //undefined

   对数组、对象、null类型都统统打印的是object类型

   举例:

console.log(typeof([1,2,3]));          //object
console.log(typeof({name:'',age:0}));  //object
console.log(typeof(null));             //object

2. instanceof:  返回的是boolean类型(可判断数组类型)

    判断依据:检测对象的原型链上是否有构造函数的prototype属性。

举例:

function Person(){
}
function Student(){
}
Student.prototype=new Person();
Student.prototype.constructor=Student;      //注:原型替换的过程(也就是继承)会失去原型对象的constructor属性,所以我们需要手动指回
console.log(new Student() instanceof Person);    //true


var arr=[1,2,3];
console.log(arr instanceof Array);         //true

3.constructor: 返回的是boolean类型(可判断数组类型)

任何一个对象都有constructor属性,指向创建这个对象的构造函数

举例:

var arr=[1,2,3];
console.log(arr.constructor==Array);

4.Object.prototype.toString.call: 方法比较通用,但是繁琐

console.log(Object.prototype.toString.call([1,2,3])=='[object Array]');        
console.log(Object.prototype.toString.call(new Date())=='[object Date]'); 
console.log(Object.prototype.toString.call(3)=='[object Number]');        
console.log(Object.prototype.toString.call('1')=='[object String]');
console.log(Object.prototype.toString.call(function(){})=='[object Function]');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值