Fourth, the conversion process in javascript string values and

The ## non-numerical data into a numerical
three methods can be converted to a non-numeric values: Number The (), the parseInt () and parseFloat () .

Number()

Number conversion rules are as follows:
1. Boolean true and false type are converted to 0 and 1;
2 is a simple digital value and return pass;
3. null, returns 0;
4. undefined, returns NaN3;
5. The string sub-process will have several cases, 0 returns an empty string, the string contains only numeric or numeric and decimal point, to convert it to the corresponding value, comprising NaN into other types of characters in addition to numbers;
6. the object, then, then call the object's valueOf (), in accordance with the foregoing conversion rules, if the result is NaN, call the object's toString (), this in accordance with the foregoing conversion rules;

Number('abc'); // NaN
Number(''); // 0
Number(true); // 1

** Note: unary operator can implement the same function as a hair and Number (). **

Number () is more complex when dealing with a string and not reasonable, therefore often used in processing of the string is the parseInt () and parseFloat ().
The parseInt () and parseFloat ()
and Number () except that:

  • Number () convert the empty string to 0, and the parseInt () and parseFloat () will convert the empty string NaN3;
  • Number () transformed values ​​rather than the entire portion of the value, parseInt () and parseFloat () just before the first character string conversion invalid character.
  • the parseInt () method can be transferred radix second parameter specifies the conversion values ​​(such as in accordance with a decimal or octal analytical analysis or the like), parseInt only resolve the decimal value;
Number The ( '123abc'); // NaN3 
the parseInt ( '123abc'); // 123 
parseFloat ( '123.45ab); // 123.45 
parseInt ('10', 2); // 2, according to binary parse 
parseInt ('10 ', 10); // 10, parse a decimal

** Note, do not specify the parseInt () method when the base, that does not pass the second parameter is determined by parseInt () to determine how to parse the string, so in order to avoid incorrect parsing, we'd never specified base .

Convert a value into a string
There are two ways to convert a value string: toString () and String ()

toString ()
except both null and undefined toString () method call toString () method in most cases not necessary to pass parameters, but the values at the time of calling toString () method, a parameter can be passed, the base output value.

String ()
function can be any type of value to a string, do not know when the converted value is null or undefined time, you can use the String () conversion method. Null can be converted to 'null', undefined Switch 'undefined'.

** In addition to a string should be a value addition operation is also made with an empty string, to achieve the same conversion object **

Guess you like

Origin www.cnblogs.com/youyang-2018/p/11701257.html