002-判断JS数据类型

1、typeof

typeof 返回一个表示数据类型的字符串,返回结果包括:number、boolean、string、object、undefined、function、symbol等7种数据类型。

举个栗子:

typeof null;  // object
typeof undefined;  // undefined
typeof 1;  // number
typeof '1';  // string
typeof [];  // object
typeof true;  // boolean
typeof function() {};  // function
typeof Symbol();  // symbol

有栗子可见,typeof对于基本类型的判断相对比较准确(null除外),对于引用类型的无能为力。下面介绍一种能判断引用类型的方法。

2、instanceof

instanceof 是用来判断 A 是否为 B 的实例对,表达式为:A instanceof B,如果A是B的实例,则返回true,否则返回false。

举个栗子

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

虽然instanceof可以判断引用类型,但是对于基本类型又无能为力了,有没有一种方式既能判断基本类型又能判断引用类型呢,请看第三种方法。

3、Object.prototype.toString .call()

举个栗子

Object.prototype.toString.call(null);  // [object Null]
Object.prototype.toString.call(undefined);  // [object Undefined]
Object.prototype.toString.call(1);  // [object Number]
Object.prototype.toString.call('1');  // [object String]
Object.prototype.toString.call([]);  // [object Array]
Object.prototype.toString.call(true);  // [object Boolean]
Object.prototype.toString.call(function(){});  // [object Function]
Object.prototype.toString.call({});  // [object Object]

到这里,我们已经可以对数据类型有了准确的判断,至于这些方法的原理是什么,请看后面的文章003-instanceof原理

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值