JS in different types of basic data can be converted between, this conversion is a rule can be found, not arbitrary random. There are 5 basic types of data in JS: String, number, Boolean, null, undefined, where the type commonly used for calculation or comparison is the first three.
Conversion between the underlying data
Other types of conversion figures
Raw data type |
Target type number |
Undefined |
NaN |
Null |
0 |
False |
0 |
True |
1 |
Number string |
The corresponding number |
A string that cannot be converted |
NaN |
Other types are converted to strings
Raw data type |
Target type string |
Undefined |
Undefined |
Null |
Null |
False |
False |
True |
True |
Digital |
Numeric string |
Addition between different types of underlying data, the data is first converted to number, and then converted to string (if there is a string type of data that participates in the operation)
Copy Code code as follows:
null + undefined//0+nan
Null + false//0+0
1 + true//1+1
1 + ' 1 '//' 11 '; Number added to string the result is a string
The result of 1 + 2 + ' 3 '//';(1+2 ' is then added to ' 3 '; Here we have to take each step apart separately to see if it turns out to be the same as the following.
1 + (2 + ' 3 ')//' 123 '; first op ' 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 participates in addition and subtraction operations
Object participates in the underlying type data operation, which is first converted to the underlying type. Call its valueof method first, if it is not the underlying type, call its ToString method, or throw an error if the returned is not the underlying type. However, the date data is just the opposite
Copy Code code as follows:
To facilitate observation of the ToString and valueof methods for 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, and the result is 2.
Re-rewrite the ToString method
Date.prototype.toString = function () {
return {};
}
var c = new Date,
d = new Date;
C + D; Call the ToString method returns not the underlying type, then call valueof,2 + 2, and the result is 4
Rewrite the valueof method again
Date.prototype.valueOf = function () {
return {};
}
var e = new Date,
f = new Date;
E + F; Error
Changing the above example to object or other type can get the corresponding result, but call valueof first, then call ToString.
The magic effect of the ' + ' number
The data has a plus ' + ' before it can be converted to a number
Copy Code code as follows:
+ ' 1 ' +1/2
+ ' s ' +2/NaN
Note: The first time, the format is not good, many flaws, welcome everyone to shoot bricks