JS中的数据类型
基本数据类型
- number
- NaN / isNaN / infinity / parseInt / Number()
- string
- boolean
- null
- undefined
- symbol
- bigint
引用数据类型
- object
- 普通对象
- 数组对象
- 正则对象
- 日期对象
- Math数学函数对象
- Map
- Set
- ...
- function
数据类型检测
JavaScript检测数据类型只有四种
- typeof 检测数据类型的运算符
- instanceof 检测是否为某个类的实例
- constructor 检测构造函数
- Object.prototype.toString.call 检测数据类型
其他类型检测
- Array.isArray()
- isNaN 但是NaN不是一个数据类型
typeof
typeof [value] 返回当前值的数据类型 "数据类型"
- 返回的结果都是字符串
- 局限性
- typeof null => 'object'
- typeof不能区分对象类型(普通对象、数组都返回'object')
let a = typeof typeof typeof [12, 23];
console.log(a);// string
- typeof NaN => 'number'
- typeof infinity => 'number'
- NaN和谁都不相等,包括和它自身也不相等
- isNaN()检测这个值是否为有效数字,如果不是有效数字则返回true,是有效数字则返回false
let res = parseFloat('left: 120px');
if (res === 120) {
console.log(120);
} else if (res === NaN) { // NaN !== NaN
console.log('NaN');
} else if (typeof res === 'number') { // typeof NaN === 'number'
console.log('number');
} else {
console.log('invalid number');
}
把其他数据类型转换成number
- 强转换(基于底层机制转换的)Number([value])
- 一些隐式转换都是基于Number完成的
- isNaN('12px') 先把其他类型转换成number再检测
- 数学运算 '12px' - 5
- '字符串' == 数字 两个等号比较的时候也需要把其他类型转换成number
- 一些隐式转换都是基于Number完成的
- 弱转换(基于一些额外的方法转换的)parseFloat([value])、parseInt([value])
parseInt和Number的区别
- parseInt()处理的是字符串,从字符串左侧开始查询有效数字字符,遇到非有效数字则停止查找
- parseInt()如果遇到的不是字符串,需要先转换为字符串再开始查找;和parseFloat()的区别是遇到小数点就停止查找
- Number()直接调用底层的数据类型检测机制来完成
-
true 1 false 0
-
'' 0
-
null 0 undefined NaN
-
字符串必须保证全是数字字符才会转换成数字
-
parseInt(''); // NaN,没有有效数字字符
Number(''); // 0, 隐式类型转换
isNaN(''); // false, 先把''转换成数字(隐式Number), isNaN(0) => false
parseInt(null); // parseInt('null') => NaN
Number(null); // 0
isNaN(null); // 先Number(null) => 0 ; parseInt(0) => 0
parseInt('12px'); // 12
Number('12px'); // NaN
isNaN('12px'); // 先Number('12px') => NaN,isNaN(NaN)=> true
parseFloat('1.6px') + parseInt('1.2px') + typeof parseInt(null); // 1.6 + 1 + 'number' = '2.6number', +遇到字符串(或者对象,因为对象就需要转换成字符串然后再处理)
isNaN(Number(!!Number(parseInt('0.8')))); // !!转换成lboolean值 isNaN (0) => false
typeof !parseInt(null) + !isNaN(null); // !NaN => true typeof true => 'boolean' 'boolean' + ture => 'booleantrue'
== 规则
- 对象 == 字符串 对象转换为字符串
- null == undefined 和其他都不相等
- 剩下两边不同都是转换为Number
[] == true; //
Number([]) => Number(true) => 0 == 1 => false
值类型转数字
- null --> 0
- '123' --> 123: 纯数字构成的字符串直接转换为应的数字
- true --> 1
- false --> 0
- '124a' --> NaN
- undefined --> NaN
- Symbol --> 抛出错误
- [] -> ''
- {} -> '[object Object]'
Object类型,先valueOf(),再toString();没有valueOf()就直接toString()
let res = 10 + false + undefined + [] + 'test' + null + true + {};
// 10 + 0 => 10
// 10 + NaN => NaN; undefined转换成Number是NaN, null转换成Number是0
// NaN + [] => NaN + '' => 'NaN'; []是对象调用toString转换成字符串 [] => '',然后是字符串拼接
// 'NaN' + 'test' => 'NaNtest'; +字符串拼接
// 遇到字符后,剩下的就是字符串拼接了
// 'NaNtestnulltrue'
// {}变成字符串 ({}).toString() => '[object Object]';
// 'NaNtestnulltrue[object Object]'