preface

JavaScript has seven data types: Number, String, Boolean, Null, Undefined, Symbol, Object. These seven data types can be converted to each other. There are two types of conversion methods: Display type conversion and implicit type conversion, master and skilled use of type conversion can not only improve the efficiency of our development, but also improve the efficiency of finding bugs

Display type conversion

Converted to Boolean

The Boolean() method is called to convert data to Boolean values. The rules for converting data to Boolean values are simple, except that false, undefined, null, 0, NaN, and “” return false. It is worth noting that **[] and {}** convert to true!! Boolean([]) // true

Is converted to a Number

There are three ways to convert non-numeric values to numeric values :Number(), parseInt(), and parseFloat().

Number()

  • Boolean values that convert true to 1 and false to 0
  • Value, return directly
  • Null returns 0
  • Undefined, return NaN
  • String, apply the following rules
    • Spaces at the beginning and end of the string are ignored
    • If the string contains numeric characters, including those preceded by plus or minus signs, it is converted to a decimal value (zeros before the value are ignored).
    • If the string contains a valid floating-point value format such as “1.1”, it is converted to the corresponding floating-point value (again, the preceding zeros are ignored).
    • If the string contains a valid hexadecimal format such as “0xf”, it is converted to the decimal integer value corresponding to the hexadecimal value.
    • If it is an empty string (containing no characters), 0 is returned.
    • If the string contains characters other than the above, NaN is returned
  • Object that calls the valueOf() method and converts the returned value according to the rules above. If the conversion results in a NaN, the toString() method is called and converted according to the rules for converting strings

The following examples of transformations help you understand the above rules

Number("") 						/ / 0
Number("") 						/ / 0
Number("+ 23423")                                / / 23423
Number("2 2") 						// NaN
Number("+ + 2") 						// NaN
Number("+ 002") 						/ / 2
Number("3.125 e7")					/ / 31250000
Copy the code

parseInt()

The parseInt() function focuses on whether a string contains a numeric pattern, and the conversion rules are similar to the Number conversion rules, with the main differences

  • If the first character is not a numeric character, plus or minus, parseInt() immediately returns NaN. This means that an empty string also returns NaN
  • If the first character is a numeric character, plus or minus, each character in turn is tested until the end of the string, or a non-numeric character is encountered
  • Returns the integer part if it is a number

The following examples of transformations help you understand the above rules

parseInt("1234blue");  / / 1234
parseInt(""); 	       // NaN
parseInt(22.5);        / / 22
parseInt("70");        / / 70
parseInt("0xf");       // 15, interpreted as a hexadecimal integer
parseInt("3.125 e7");   / / 3
Copy the code

Different numeric formats can be confusing, so parseInt() also takes a second argument that specifies the base (base). If you know that the value to be parsed is hexadecimal, you can pass 16 as the second argument to parse correctly: let num = parseInt(“0xAF”, 16); // 175 In fact, if a hexadecimal argument is provided, then the “0x” before the string can be omitted: let num1 = parseInt(“AF”, 16); // 175 let num2 = parseInt(“AF”); // NaN In this example, the first conversion is correct and the second conversion fails. The difference is that, for the first time, we pass in a base number as an argument, telling parseInt() to parse a hexadecimal string. The second conversion detects that the first character is a non-numeric character and automatically stops and returns NaN. With the second parameter, you can greatly expand the type of results obtained after the transformation. Such as:

parseInt("10".2); // 2
parseInt("10".8); // 8
Copy the code

parseFloat()

The parseFloat() function works like the parseInt() function, except that

  • The first decimal point is valid, but the second one is invalid
  • Always ignore the beginning of the string

The following examples of transformations help you understand the above rules

parseFloat("1234blue");  / / 1234
parseFloat("0xA");	 / / 0
parseFloat(22.5);        / / 22.5
parseFloat("22.34.5");   / / 22.34
parseFloat("0908.5"); 	 / / 908.5
parseFloat("3.125 e7");	 / / 31250000
Copy the code

Convert a String

There are three ways to convert non-strings to strings: toString(), String(), and json.stringify ().

toString()

The toString() method is typically used for numeric values, booleans, objects, and strings. Null and undefined have no toString() method

String()

The String() function follows these rules

  • If the value has a toString() method, that method is called (with no arguments) and the result is returned
  • If the value is null, return “null”.
  • If the value is undefined, return undefined

You want objects and arrays to be converted to strings using the above method, which does not have the desired effect

let arr = [ 1.2 ]
let obj = { age: 18 }
arr.toString() / / 1, 2, ""
String(arr) / / 1, 2, ""
obj.toString() // "[object Object]"
String(obj) // "[object Object]"
Copy the code

JSON.stringify()

To convert arrays and objects to strings, use the json.stringify () method

let obj = {
  id: 1.persong: { age: 18}};JSON.stringify(obj) // "{\"id\":1,\"persong\":{\"age\":18}}"
Copy the code

Implicit type conversion

Sometimes we encounter when operators in the operation, if both sides do not have a unified data type, CPU cannot be computed, then the compiler will automatically the data on both sides of the operators to do a data type conversion, converted to the same data type in operation, this need not programmers manual conversion, the compiler will automatically convert way is called an implicit conversion

Converted to Boolean

Converts a non-Boolean value to a Boolean value using the Boolean() method

  1. If conditional judgment
  2. The Boolean operator (! , &&, | |)
  3. Do -while condition judgment
  4. Ternary operator conditional judgment

Is converted to a Number

The value is converted to a numeric value using the Number() method

  1. ++ —
let age = "20"
age++
++age
Copy the code
  1. One dollar plus and one dollar minus

+ "2.2" / 2.2 /

  1. Operator (|, &, ~ ^, < <, > >, > > >)

“12.2” | 0 / / 12 which can be used in the integer

  1. Multiplicative operator (*,/,%)

2 * "2"        // 4 

  1. The additive operator (+,-)

3 - "2"    // 1

“+” in the presence of a String, the String() method is called to concatenate the String

  1. Exponential operator

3 ** "2"    // 9

  1. Relational operators (>,<,>=,<=)
  • If one of the operands is a value, call Number() to convert the other operand to a value
  • If one of the operands is a Boolean, Number() is called to convert the operand to a value
  1. = =! =

Convert a String

Call the String() method to convert a non-string to a String

  1. The additive operator (+)

“5” // “55”

conclusion

Temporarily oneself can think of so much, welcome each big guy to supplement