js中的数据类型

基本数据类型

number

NaN:不是一个有效数字(除了数字什么都是)

  1. NaN和谁都不相等 NaN!=NaN
  2. parseInt:处理的值是字符串,先将值转化为字符串,从字符串左侧开始查找有效数字字符(遇到非有效字符则停止查找)如果处理的值不是字符串,则需要先转化为字符串然后再开始查找
  3. Number:直接调用浏览器最底层的数据类型检测机制来完成
    1. true -> 1 false -> 0
    2. null -> 0 undefined -> NaN
    3. 字符中必须保证都是有效数字才会转换为数字,否则都是NaN
  4. isNaN(值) 检测这个值是否为有效数字,如果不是有效数字返回true,如果是有效数字返回false
  5. parseFloat(‘值’) 返回有效数字 从第一位开始判断,如果为有效数字则继续向后判断直到不为有效数字停止返回有效数字,如果第一位不为有效数字则返回NaN

    把其他数据类型转数字

    强转换(基于底层机制的转换)Number()
    一些隐式转换都是基于Number完成的
    isNaN(‘12px’) 先把其他类型值转化为数字再检测
    数学运算 ‘12px’-13
    字符串==数字 两个等号很多时候也是要把其他值转化为数字

    弱转换(基于一些额外的方法转换)parseInt()/parseFloat()

    Infinity

    -Infinity

    例题


    1. parseInt("") //NaN
    2. Number("") //0
    3. isNaN("")//先把空字符串转化为数字(隐式Number) -> isNaN(0) = false
    4. parseInt(null) // parseInt('null') = NaN
    5. Number(null) //0
    6. isNaN(null) // isNaN(0) = false
    7. parseInt("12px") //12
    8. Number("12px") // NaN
    9. isNaN("12px") //isNaN(NaN) = true
    10. parseFloat('1.6px')+parseInt('1.2px')+ typeof parseInt(null) //1.6 + 1 +typeof NaN ->2.6+number = '2.6number
    11. isNaN(Number(!!Number(parseInt('0.8'))))//isNaN(Number(false)) -> false
    12. typeof !parseInt(null) +!isNaN(null)
  6. 双等号 []==true 都转化为数字,Number([]) =0 Number(true)=1,所以 []==true 返回false

  7. 10 + 0 ->10

10+ undefined -> NaN
NaN + [] -> ‘NaN’
‘NaN’ + ‘Tencent’ -> NaNTencent
‘NaNTencentnulltrue[object Object]’

  1. let result = 10 + false + undefined + [] + "Tencent" + null + true + {}; //NaNTencentnulltrue[object Object]

string

boolean

undefine

null

symbol

bigint

引用数据类型

function

object

普通对象
数组对象
正则对象
日期对象
Math对象

数据类型检测

typeof:检测数据类型的逻辑运算符

typeof value 返回当前值的数据类型‘数据类型’
返回的结果都是字符串
局限性:
typeof null => ‘object’
typeof 不能细分对象(检测普通对象和数组返回都是’object’)
所有的值在内存中都是二进制存储的,typeof将 全为000的值 视为object,所以typeof null 为object

  1. console.log(typeof 12) //number
  2. console.log(typeof '12')//string
  3. console.log(typeof true)//boolean
  4. console.log(typeof null)//object
  5. console.log(typeof undefined)//undefined
  6. console.log(typeof NaN)//number
  7. console.log(typeof Symbol('1'))//symbol
  8. console.log(typeof BigInt('1'))//bigint
  9. console.log(typeof {})//object
  10. console.log(typeof [])//object
  11. console.log(typeof function(){})//function

  1. let a = typeof typeof typeof [12,30]
  2. console.log(a) //'string'

instanceof:检测是否为某个类的实例
constructor:检查构造函数
Object.porototype.toString.call:检测数据类型