js中检测数据类型的方式有哪些?

1.typeof

console.log(typeof 2); //number
console.log(typeof null); //object
console.log(typeof undefined); //underfined
console.log(typeof {}); // object
console.log(typeof []); // object
console.log(typeof function(){}); // function
console.log(typeof 'str'); // string
console.log(typeof true); // boolean

其中数组、对象、null都会被判断为Object,其他判断都正确

2. instanceof

console.log(2 instanceof Number);  //false
console.log(true instanceof Boolean); //false
console.log('str' instanceof String); //false

console.log([] instanceof Array); //true
console.log(function(){} instanceof Function); //true
console.log({} instanceof Object); //true

可以看到instanceof 只能正确判断引用数据类型,而不能判断基本数据类型。 instanceof运算符可以用来测试一个对象在其原型链中是否存在一个构造函数的protype属性。

3.construtor

const obj = {}
const fn = function Fn(){}
const str = ''
console.log(obj.constructor); //Object
console.log(fn.constructor); // function
console.log(str.constructor); // String

construtor 有两个作用,一是判断数据类型,二是对象实例通过construtor对象访问它的构造函数。需要注意,如果创建一个对象来改变它的型,constructor就不能判断数据类型了:

function Fn(){}
Fn.protype = new Array()
let f = new Fn()
console.log(f.constructor === fn); // fales
console.log(f.constructor === Array); // true

4.Object.prototype.toString.call()

Object.prototype.toString.call() 使用Object对象的原型方法toString来判断数据类型:

const type = Object.prototype.toString
console.log(type.call(2));
console.log(type.call('2'));
console.log(type.call(null));
console.log(type.call(undefined));
console.log(type.call([]));
console.log(type.call({}));
console.log(type.call(function(){}));
console.log(type.call(true));;

应该就这四种方法了,希望对您有帮助。。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值