We can convert from String to Number by Number
, parseInt
, +
or ~~
operator.
Version
ECMAScript 2015
Number
let x = '123'
Number (x) // ?
Number
is a constructor function to create a Wrapper Object bynew
Number
is a normal function to convert from String to Number
parseInt
let x = '123'
parseInt (x) // ?
We can also use parseInt
to convert from String to Number.
+ Operator
let x = '123';
+x // ?
We can also use +
operator to convert from String to Number.
~~ Operator
let x = '123'
~~x // ?
~
is a bitwise NOT operator, it convert to Number first, just like-n - 1
~~
is-(-n - 1) - 1
, it equals to(n + 1) - 1
, and back ton
Conclusion
Number
andparseInt
is the most intuitive way to convert from String to Number+
operator is the shortest way to convert from String to Number
Reference
Dr.Axel Rauschmayer, Speaking JavaScript
Bret Cameron, 12 JavaScript Tricks You Won’t Find in Most Tutorials