js中的数据类型
基本数据类型
number
NaN:不是一个有效数字(除了数字什么都是)
- NaN和谁都不相等 NaN!=NaN
- parseInt:处理的值是字符串,先将值转化为字符串,从字符串左侧开始查找有效数字字符(遇到非有效字符则停止查找)如果处理的值不是字符串,则需要先转化为字符串然后再开始查找
- Number:直接调用浏览器最底层的数据类型检测机制来完成
- true -> 1 false -> 0
- null -> 0 undefined -> NaN
- 字符中必须保证都是有效数字才会转换为数字,否则都是NaN
- isNaN(值) 检测这个值是否为有效数字,如果不是有效数字返回true,如果是有效数字返回false
parseFloat(‘值’) 返回有效数字 从第一位开始判断,如果为有效数字则继续向后判断直到不为有效数字停止返回有效数字,如果第一位不为有效数字则返回NaN
把其他数据类型转数字
强转换(基于底层机制的转换)Number()
一些隐式转换都是基于Number完成的
isNaN(‘12px’) 先把其他类型值转化为数字再检测
数学运算 ‘12px’-13
字符串==数字 两个等号很多时候也是要把其他值转化为数字
…
弱转换(基于一些额外的方法转换)parseInt()/parseFloat()Infinity
-Infinity
例题
parseInt("") //NaNNumber("") //0isNaN("")//先把空字符串转化为数字(隐式Number) -> isNaN(0) = falseparseInt(null) // parseInt('null') = NaNNumber(null) //0isNaN(null) // isNaN(0) = falseparseInt("12px") //12Number("12px") // NaNisNaN("12px") //isNaN(NaN) = trueparseFloat('1.6px')+parseInt('1.2px')+ typeof parseInt(null) //1.6 + 1 +typeof NaN ->2.6+number = '2.6numberisNaN(Number(!!Number(parseInt('0.8'))))//isNaN(Number(false)) -> falsetypeof !parseInt(null) +!isNaN(null)
双等号 []==true 都转化为数字,Number([]) =0 Number(true)=1,所以 []==true 返回false
- 10 + 0 ->10
10+ undefined -> NaN
NaN + [] -> ‘NaN’
‘NaN’ + ‘Tencent’ -> NaNTencent
‘NaNTencentnulltrue[object Object]’
let result = 10 + false + undefined + [] + "Tencent" + null + true + {}; //NaNTencentnulltrue[object Object]
string
boolean
undefine
null
symbol
bigint
引用数据类型
function
object
数据类型检测
typeof:检测数据类型的逻辑运算符
typeof value 返回当前值的数据类型‘数据类型’
返回的结果都是字符串
局限性:
typeof null => ‘object’
typeof 不能细分对象(检测普通对象和数组返回都是’object’)
所有的值在内存中都是二进制存储的,typeof将 全为000的值 视为object,所以typeof null 为object
console.log(typeof 12) //numberconsole.log(typeof '12')//stringconsole.log(typeof true)//booleanconsole.log(typeof null)//objectconsole.log(typeof undefined)//undefinedconsole.log(typeof NaN)//numberconsole.log(typeof Symbol('1'))//symbolconsole.log(typeof BigInt('1'))//bigintconsole.log(typeof {})//objectconsole.log(typeof [])//objectconsole.log(typeof function(){})//function
例
let a = typeof typeof typeof [12,30]console.log(a) //'string'
instanceof:检测是否为某个类的实例
constructor:检查构造函数
Object.porototype.toString.call:检测数据类型
