Different types of basic data in JS can be converted. This conversion is regular, not random and random. There are 5 basic types of data in JS: String, Number, Boolean, NULL, Undefined. Among them, the types of calculation or comparison are the first three types.
Conversion between basic data
| Original data type | Target type Number |
| undefined | Nan |
| null | 0 |
| False | 0 |
| true | 1 |
| Digital string | Corresponding number |
| String that cannot be transformed | Nan |
| Original data type | Target type string |
| undefined | undefined |
| null | null |
| False | False |
| true | true |
| number | Numeral string |
The addition of different types of basic data, the data is converted to Number first, and then converted to string (if there is a String type data to participate in the operation)
Copy code code as follows:
null + undefined // 0 + nan
null + false // 0 + 0
1 + true // 1 + 1
1 + '1' /// '11;
1 + 2 + '3' // '33'; (1 + 2) the results of the (1 + 2) then add to the '3'; here is to be removed by each step to be opened separately, otherwise it will become the same result as the following.
1 +(2 +'3') // '123'; first operation 2 +'3', then 1 +'23 '
's' + null // 'snull'
's' + undefined // 'sundefined'
's' + true // 'strue'
1+TRUE+UNDEFINED+'S' // 1+1+NAN+'S' = 2+Nan+'S' = NAN+'S' = Nans
Object participation of addition and subtraction method
The object participates in the basic type of data operation, and first translates into the basic type. First call the valueOf method. If the basic type is returned, and then call its tostring method. If the back is not the basic type, it is wrong. However, date data is just the opposite
Copy code code as follows:
// In order to facilitate observing the Tostring method and valueof method of rewriting 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, the result is 2
// Rewrite it again
Date.prototype.tostring = Function () {
Return {};
}
var c = new date,
d = new date;
C + d; // Call the tostring method to return is not the basic type, and then call the valueof, 2 + 2, the result is 4
// Rewrite the Valueof method
Date.prototype.valueof = Function () {
Return {};
}
var e = new date,
f = new date;
E + F; // Error
The above example can be replaced with Object or other types to get the corresponding results, but first call Valueof and then call Tostring.
The magic effect of '+'
There is a number '+' in front of the data, which can be converted into a number
Copy code code as follows:
+'1'+1 // 2
+'s'+2 // nan
Note: For the first time, the format is not good, and there are many omissions. Welcome everyone to shoot bricks