① using Parseint/parsefloat (number.parseint/number.parsefloat in ECMAScript6)
1Console.log (parseint (' A10 '));//NaN2Console.log (parseint (' 1a0 '));//13Console.log (parseint (' 10a '));//Ten4Console.log (parseint (' 10 '));//Ten5 6Console.log (parsefloat (' a10.1 '));//NaN7Console.log (parsefloat (' 1a0.1 '));//18Console.log (parsefloat (' 10a.1 '));//Ten9Console.log (parsefloat (' 10.1a '));//10.1TenConsole.log (parsefloat (' 10.1 '));//10.1
② using the ' + ' operator
1Console.log (+ ' A10 ');//NaN2Console.log (+ ' 1a0 ');//NaN3Console.log (+ ' 10a ');//NaN4Console.log (+ ' 10 ');//Ten5 6Console.log (+ ' a10.1 ');//NaN7Console.log (+ ' 1a0.1 ');//NaN8Console.log (+ ' 10a.1 ');//NaN9Console.log (+ ' 10.1a ');//NaNTenConsole.log (+ ' 10.1 ');//10.1
Although you can convert a string to a number in both ways, the obvious conversion is different. When a string-to-numeric conversion is performed using Parseint/parsefloat, the characters in the string are parsed one after the other until the parsed character ends, and the parsed portion is converted to a numeric return. However, when a string-to-number conversion is performed in this way using the ' + ' operator, it returns Nan directly as long as there are characters in the string that cannot be parsed. This is the difference between the two modes of conversion, please note the distinction.
JavaScript Learning notes: 2 ways to convert strings to numbers