You can get a numeric value from a string using parseInt(), this method accepts another radix argument, which is often omitted, but shouldn't be. There may be problems when the string starts with "0". For example, when entering a form field part of the time, in ECMAScript 3, strings starting with "0" are treated as octal, but this has been done in Changed in ECMAScript 5. To avoid contradictions and unexpected results, always specify radix arguments.
var month = "05", year = "09"; month = parseInt(month, 10); year = parseInt(year, 10); alert(month); alert(year);
In this example, if you ignore the base parameter, such as parseInt(year), the returned value will be 0, because "09" is treated as octal (such as executing parseInt(year, 8)), and 09 is in It is not a valid number in base 8.
Replacement methods convert strings to numbers, including:
+"08" // 结果是 8 Number("08") // 8
These are usually faster than parseInt() because the parseInt() method, as the name implies, does not simply parse and convert. However, if you want to enter, for example, "08 hello", parseInt() will return a number, and otherwise end up with NaN.