JS之数据类型转换

数据类型转换

其他类型转为字符串(string)

1. x.toString()

console.log理论上只能接受字符串:
console.log(1)将转换成console.log( (1).toString() )

2. String(x)


3. 简便方法: x + ''

> 1+'1'
< '11'
等价于(1).toString()+'1'

其他类型转为数值(number)

  1. Number(x)
  2. parseInt(x,10), 10为转为十进制,MDN详细介绍
  3. parseFloat(x),MDN详细介绍
  4. x - 0
  5. + x

方法4最常用;方法2面试题常考。

其他类型转为布尔(Boolean)

1. Boolean(x)
2. !!x
当转为布尔值时,共有五个falsy值,分别为:

  • o
  • NaN
  • ''
  • null
  • undefined

转载于:https://juejin.im/post/5d060078f265da1b667bd9b1

猜你喜欢

转载自blog.csdn.net/weixin_34092370/article/details/93180532