This article mainly introduces how to convert operations between different types of javascript data. For more information, see converting basic data of different types in javascript, there are rules to find such conversions, and they are not random. In JavaScript, there are five basic types of data: string, number, boolean, null, and undefined. Among them, the first three types are commonly used for calculation or comparison.
Conversion between basic data
Other types of conversion numbers
Raw Data Type |
Target type Number |
Undefined |
NaN |
Null |
0 |
False |
0 |
True |
1 |
Numeric string |
Corresponding number |
String that cannot be converted |
NaN |
Convert other types to strings
Raw Data Type |
Target type String |
Undefined |
Undefined |
Null |
Null |
False |
False |
True |
True |
Number |
Numeric string |
For addition between different types of basic data, data is first converted to number and then to string (if there is a string type of data involved in the operation)
The Code is as follows:
Null + undefined // 0 + NaN
Null + false // 0 + 0
1 + true // 1 + 1
1 + '1' // '11'; the number is added to the string and the result is a string.
1 + 2 + '3' // '33'; (1 + 2) the result is then added with '3'; here we need to separate each step of addition, otherwise, the result will be the same as the following.
1 + (2 + '3') // '123'; Calculate 2 + '3' first, then 1 + '23'
'S '+ null // 'snull'
'S '+ undefined // 'sundefined'
'S '+ true // 'strue'
1 + true + undefined + 's' // 1 + 1 + NaN + 's' = 2 + NaN + 's' = NaNs
Objects involved in addition and subtraction
The object is involved in basic type data calculation and first converted to basic type. Call its valueOf method first. If the returned result is not of the basic type, call its toString method. If the returned result is not of the basic type, an error is thrown. However, the Date data is the opposite.
The Code is as follows:
// To facilitate observation and rewriting of the toString and valueOf methods of Date
Date. prototype. toString = function (){
Return 1;
}
Date. prototype. valueOf = function (){
Return 2;
}
Var a = new Date,
B = new Date;
A + B; // call toString, 1 + 1, and the result is 2
// Rewrite the toString method.
Date. prototype. toString = function (){
Return {};
}
Var c = new Date,
D = new Date;
C + d; // call the toString method to return a value that is not of the basic type. Then call valueOf, 2 + 2, and the result is 4.
// Rewrite the valueOf method.
Date. prototype. valueOf = function (){
Return {};
}
Var e = new Date,
F = new Date;
E + f; // Error
Replace the above example with an Object or another type to get the corresponding result, but call valueOf first and then toString.
The magic of '+'
There is a plus sign '+' before the data to convert the string to a number.
The Code is as follows:
+ '1' + 1 // 2
+'S '+ 2 // NaN
NOTE: For the first time, the format is poor and there are many leaks. You are welcome to make a brick.