如何判断JavaScript中的数据类型?

八种数据类型

在最新的JavaScript标准中,一共有8种数据类型,分别是基础类型number、string、boolean、null、undefined、bigInt、symbol,引用类型:Object。其中bigInt和symbol是es6新引入的两种基础类型,bigInt可以用来声明超出最大安全边界的数字类型,SymBol用来声明唯一的变量。

typeof用来判断基础数据类型和function

typeof用来判断基础数据类型和function,不能判断null和引用类型

typeof(1); // 'number'
typeof(‘str’);// 'string'
typeof(true);// 'boolean'
typeof(1000n);// 'bigint'
typeof(Symbol('symbol'));// 'symbol'
typeof(undefined);// 'undefined'
typeof(()=>{}); //'function'
typeof(null); //Object
typeof([]); //'Object'
typeof({});//'Object'

instance of 用来判断引用类型的数据

instance of用来判断某个变量是某个对象的实例,返回布尔值。 经常用来判断引用类型的数据,只能判断用构造函数生成的基础数据类型,不能判断用字面量声明的基础类型。

引用类型:

var obj = {}; obj instanceof Object; // true
var arr =[];  arr instanceof Object; // true
var date = new Date();; date instanceof Object; // true

使用构造函数声明的基础类型数据:

var str = new String('str');
bar num = new Number(5);
str instance of String; //true
num instance of Number;// true

使用字面量声明的基础类型:

var str1 = 'str';
var num1 = 5;
str1 instance of String; //false
num1 instance of Number;// false

使用constructor进行判断

function checkType(variable,constructor){
 return variable?.constructor === constructor;
};
checkType(1,Number); //true
checkType('str',String); //true
checkType(true,Boolean); //true
checkType({},Boolean); //true
checkType([],Boolean); //true
checkType(()=>{},Function); //true
checkType(1000n,BigInt); //true
checkType(Symbol(1),Symbol); //true
checkType(undefined,undefined); //true
checkType(null,null); //false

除了null其它都能判断

Object.prototype.toString.call()

Object.prototype.toString.call(1); //'[object Number]'
Object.prototype.toString.call('str'); //'[object String]'
Object.prototype.toString.call(true);// '[object Boolean]'
Object.prototype.toString.call(1000n);// '[object BigInt]'
Object.prototype.toString.call(Symbol(1));// '[object Symbol]'
Object.prototype.toString.call({}); // '[object Object]'
Object.prototype.toString.call([]);// '[object Array]'
Object.prototype.toString.call(()=>{});//'[object Function]'
Object.prototype.toString.call(null);//'[object Null]'
Object.prototype.toString.call(undefined);'[object Undefined]'

总结:

  1. typeof 用来判断基础类型和function ,不能判断null。
  2. instance of用来判断引用类型的数据和自定义的对象,还能用来判断使用构造函数声明的基础数据类型,不能判断null。
  3. construct能判断除null以外的所有类型。
  4. Object.prototype.toString.call();能判断出所有的数据类型,在进行简单封装后可以直接使用。
  5. null是个比较特殊的存在,因为它没有构造函数所有construct和instance都不能判断null。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值