js中检测数据类型的方法及使用

第一种 typeof
一般主要用来检测基本数据类型,因为它检测引用数据类型返回的都是object

console.log(typeof "langshen");       // String
console.log(typeof 666);              // Number
console.log(typeof true);             // Boolean
console.log(typeof false);            // Boolean
console.log(typeof function(){});     // Function
console.log(typeof undefined);        // Undefined
console.log(typeof null);             // Object
console.log(typeof []);               // Object
console.log(typeof {});               // Object

typeof局限性:当 typeof 检测基本数据类型(Number、String、Boolean 、Undefined、Null)的时候是没有问题的。
但是检测引用型数据类型(Array、Object、RegExp等)的时候全都是 Object。
第二种 instanceof
这个方法主要是用来准确地检测引用数据类型(不能用来检测基本数据类型)

console.log("langshen" instanceof String);         //false
console.log(666 instanceof Number);                //false
console.log(true instanceof Boolean);              //false
console.log(null instanceof Null);
console.log(undefined instanceof Undefined);
console.log([] instanceof Array);                  //true
console.log(function(){} instanceof Function);     //true
console.log({} instanceof Object);                 //true

前三个都是以对象字面量创建的基本数据类型,但是却不是所属类的实例,只有实例方式创建出来的才是标准的对象数据类型值
instanceof是一个操作符,返回值是一个布尔值
instanceof是检测引用数据类型,而不能检测基本数据类型
第三种、constructor
constructor这个属性存在于构造函数的原型上,指向构造函数,对象可以通过 proto 在其所属类的原型上找到这个属性

console.log(("1").constructor === String);             //true
console.log((1).constructor === Number);              //true 
console.log((true).constructor === Boolean);         //true
console.log(([]).constructor === Array);             //true
console.log((function() {}).constructor === Function);    //true
console.log(({}).constructor === Object);            //true

第四种 Object.prototype.toString.call()
可以用来准确地检测所有数据类型(最好用的方法)

Object.prototype.toString.call([])
//"[object Array]"

Object.prototype.toString.call(1)
//"[object Number]"

Object.prototype.toString.call(null)
//"[object Null]"

Object.prototype.toString.call(undefined)
//"[object Undefined]"

Object.prototype.toString.call(true)
//"[object Boolean]"

Object.prototype.toString.call('111')
//"[object String]"

Object.prototype.toString.call({})
//"[object Object]"

Object.prototype.toString.call(function add(){})
//"[object Function]"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值