数据类型
es6之前
基础数据类型:Number、String、Boolean、Null、undefined
引用数据类型:Object,包含Function、Array、Date
es6新增
Symbol、BigInt、Map、Set、WeekMap、WeekSet
判断数据类型
使用typeof来判断基础数据类型
typeof(1) //number
typeof("1") //string
typeof(true) //boolean
typeof(undefined) //undefined
typeof(null) //object
typeof([]) //object
typeof({}) //object
typeof(function () { }) //function
typeof (BigInt('1')) //bigint
typeof (1n) //bigint
这里用的方法是用instanceof属性判断数据的原型是否是指定的数据类型,主要判断引用数据类型
var obj = {};
obj instanceof Object; //true
var arr = [];
arr instanceof Array; //true
var now = new Date();
now instanceof Date; //true
var func = function(){};
func instanceof Function; //true
var str = new Date();
str instanceof Date; //true
var str = "string";
str instanceof String; //false
当然,也可以直接通过prototype属性获取对象原型,来进行判断
Object.prototype.toString.call(data):
//[object String] 字符串
//[object Number] 数字
//[object Boolean] 布尔值
//[object Undefined] undefined
//[object Null] null
//[object Array] 数组
//[object Function] 函数
//[object Object] 对象
//[object RegExp] 正则表达式
//[object Date] 日期对象
判断数据类型时的注意项
- 使用typeof判断时,Array和Object数据类型都是Object类型;
- 使用typeof判断时,null类型也被认为是Object类型;
- BigInt类型数据,可以通过数字后加n(例:1n)的方式声明,所以这种组合形式的数据会被判断为BigInt;
- instanceof属性,主要是通过原型链进行判断数据类型,所以只有引用类型数据判断时才会成功;
- 使用这些方法 +new Date()、(new Date()).valueOf()、Number(new Date()),都可以获取到和new Date().getTime() 方法一样的时间戳;
- Map是[key,value]键值对组成的数组,不允许key重复;
- Set是数组,不允许数组内值重复,如果是对象无法识别;
- WeakMap 的key只能是Object类型;
- WeakSet 只能是Object对象的集合,而不能是任何类型的任意值;