JS数据类型以及数据类型转换

JS数据类型转换小计
数据类型
  • 最新的ECMAScript标准定义了7种数据类型

原始类型程序员

  1. Boolean
  2. Null
  3. Undefined
  4. Number
  5. String
  6. Symbol

对象函数

7.Objectcode

显式类型转换
  • Number函数

原始类型转换对象

数值:转换后仍是原来的值ip

console.log(Number(123)) //123字符串

字符串:若是能够被解析为数值,则转换为相应的数值,不然获得NaN.空字符串转为0编译器

console.log(Number('123')) //123string

console.log(Number('123abc')) //NaNio

console.log(Number('')) //0console

布尔值:true转换为1,false转换为0

console.log(Number(true)) //1

console.log(Number(false)) //0

undefined:转换为NaN

console.log(Number(undefined)) //NaN

null:转换为0

console.log(Number(null)) //0

对象类型转换

  1. 先调用对象自身的valueOf方法,若是该方法返回原始类型的值(数值,字符串和布尔),则直接对该值使用Number方法,再也不进行后续步骤。
  2. 若是valueOf方法返回复合类型的值,再调用对象自身的toString方法,若是toString方法返回原始类型的值,则对该值使用Number方法,再也不进行后续步骤。
  3. 若是toString方法返回的是复合类型的值,则报错。

    console.log(Number({a:1})) //NaN

    原理流程:

    a.valueOf() //{a:1}

    a.toString() //"[object Object\]"

    Number("[object Object]") //NaN

  • String函数

    原始类型转换

    数值:转为相应的字符串

    字符串:转换后仍是原来的值

    布尔值:true转为'true',false转为'false'

    undefinde:转为'undefined'

    null:转为'null'

对象类型转换

  1. 先调用toString方法,若是toString方法返回的是原始类型的数值,则对该值使用string方法,再也不进行如下步骤。
  2. 若是toString方法返回的是复合类型的值,再调用valueOf方法,若是valueOf方法返回的是原始类型的值,则对该值使用String方法,再也不进行如下步骤。
  3. 若是valueOf方法返回的是复合类型的值,则报错。
  • Boolean函数

原始类型转换

undefined:转为false

null:转为false

0:转为false

NaN:转为false

''(空字符串):转为false

以上通通都转为false,其它转为true

隐式类型转换
在js中,当运算符在运算时,若是两边数据不统一,CPU就没法计算,这时咱们编译器会自动将运算符两边的数据作一个数据类型转换,转成同样的数据类型再计算.这种无需程序员手动转换,而由编译器自动转换的方式就称为隐式转换
  • typeof

typeof underfined = 'ndefined'

typeof null = 'object'

typeof Boolean = 'function'

typeof Number = 'function'

  • 常见小坑
此类问题中:+ 分为两种状况

字符串链接符:+ 号两边有一边是字符串,会把其它数据类型调用String()方法转换成字符串而后拼接。

算术运算符:+ 号两边都是数字,会把其它数据调用Number()方法转换成数字而后作加法运算

console.log(1 + true); //算书运算符:1 + Number(true) = 1 + 1 = 2

console.log(1 + 'true'); //字符串链接符:String(1) + 'true' = '1' + 'true' = '1true'

console.log(1 + undefined)//算书运算符:1 + Number(undefined) = 1 + 0 = 1

console.log(1 + null)//算书运算符:1 + Number(null) = 1 + 0 = 1

  • 大坑&%……&¥&%……(&))已吐。。。。。
相关文章
相关标签/搜索