Implicit
Explicit
- Use the
Boolean()
,Number()
, andString()
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
- + operator: if one of the operands is a string, others are all converted to strings, example.
x + "" // => String(x)
- 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.
- 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() -- 小数点后位数.C
onverts 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
- parseInt() only parses integers
Object to Primitive Conversions
TBD