八种数据类型
在最新的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]'
总结:
- typeof 用来判断基础类型和function ,不能判断null。
- instance of用来判断引用类型的数据和自定义的对象,还能用来判断使用构造函数声明的基础数据类型,不能判断null。
- construct能判断除null以外的所有类型。
- Object.prototype.toString.call();能判断出所有的数据类型,在进行简单封装后可以直接使用。
- null是个比较特殊的存在,因为它没有构造函数所有construct和instance都不能判断null。