Javascript 004: Type Conversion

Implicit

Explicit

  • Use the Boolean()Number(), and String() functions

        

        Note: toString() is an alternative for String() among most objects other than null or undefined

        Number() only works for base-10 integers and does not allow trailing characters that are not part of the literal.

  •  Use operators
  1. + operator: if one of the operands is a string, others are all converted to strings, example.
    x + "" // => String(x)
  2. Unary + operator:converts its operand to a number, example.
    +x // => Number(x)

           Note: Unary operators are those acting upon a single operand to produce a new value.

  1. Unary ! operator: converts its operand to a boolean and negates it, example.
    !!x // => Boolean(x): Note double !
  • Use toString() for numbers: convert numbers to string with oprtional base/radix, example. 
let n = 17;
let binary = "0b" + n.toString(2);  // binary == "0b10001"
let octal = "0o" + n.toString(8);   // octal == "0o21"
let hex = "0x" + n.toString(16);    // hex == "0x11"
  • Use toFixed(), toExponential(), toPrecision() for scientific numbers
    • toFixed() -- 小数点后位数.Converts a number to a string with a specified number of digits after the decimal point.  
    • toPrecision() -- 控制有效数字. Converts a number to a string with the number of significant digits you specify
    • toExponential() -- 科学计数法 Converts a number to a string using exponential notation. 参数为小数点后位数,小数点前永远只有1位,
let n = 123456.789;
n.toFixed(0)         // => "123457"
n.toFixed(2)         // => "123456.79"
n.toFixed(5)         // => "123456.78900"
n.toExponential(1)   // => "1.2e+5"
n.toExponential(3)   // => "1.235e+5"
n.toPrecision(4)     // => "1.235e+5"
n.toPrecision(7)     // => "123456.8"
n.toPrecision(10)    // => "123456.7890"
  • Use parseInt() or parseFloat() -- more flexible alternative to Number() for String -> number conversion
    • parseInt() only parses integers
      • Begins with “0x” or “0X”, interpret as hex
      • Skip leading whitespace
      • Parse as many numeric characters as they can, and ignore anything that follows
      • If first nonspace character is not part of a valid numeric literal, they return NaN
    • parseFloat() parses both integers and floating-point numbers
      • Skip leading whitespace
      • Parse as many numeric characters as they can, and ignore anything that follows
      • If first nonspace character is not part of a valid numeric literal, they return NaN

Object to Primitive Conversions

TBD

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值