Data type classification
Basic data types
- string
- number
- boolean
- object
- function
- symbol
Reference data type
- Object
- Date
- Array
A data type that does not contain any values
- null
- undefined
Conversion between data
The other data types are converted to Number
Conversion method
- Number(val)
- parseInt/parseFloat(val)
Number
The browser’s internal default Number conversion is being calculated
Number("1"); / / 1
Number(""); / / 0
Number(""); / / 0
Number("1 2"); // NaN
Number(true); / / 1
Number(null); / / 0
Number(undefined); // NaN
Number("12px"); // NaN
Copy the code
Conclusion:
- The Boolean value is converted to the number 1 or 0
- Null is converted to the number 0
- The empty string is converted to the number 0
- Undefined becomes NaN. Any number plus NaN equals NaN
- Anything that is not a number in a string will be converted to NaN
parseInt/parseFloat
ParseFloat: Converts a string to an integer, as the name suggests
ParseFloat: Converts a string to a float
parseInt("1.1"); / / 1
parseFloat("1.1"); / / 1.1
parseInt("10px"); / / 10
parseInt(""); // NaN
parseInt(null); // NaN
parseInt(undefined); // NaN
parseInt("asd"); // NaN
Copy the code
Conclusion:
- Start with the first character on the left and stop at non-numbers
- ParseFloat recognizes one more decimal point than parseFloat
- Anything that is not a number in a string will be converted to NaN
Other data is converted to String
Conversion method
- toString(val)
- String(val)
String(123); / / "123"
String(123 + 1); / / "124"
(123).toString(); / / "123"
(123 + 1).toString(); / / "124"
[1.2].toString(); / / 1, 2, ""
new Date().toString(); // "Wed Sep 02 2020 17:25:51 GMT+0800"
(123 + "1").toString(); / / "1231"
Copy the code
If a string or object appears to the left of the + sign, it is concatenated as string
Other data is converted to Boolean
The rules
-
Only 0, NaN, null, undefined, and empty string values will be converted to false, and the rest will be true
-
implicit
- In condition judgment, the result of condition processing is Boolean value
-
explicit
- ! Invert after converting to a Boolean value
- !!!!! Take the inverse and then take the inverse
- Boolean(val)
Boolean(undefined); // false
Boolean(0); // false
Boolean(NaN); // false
Boolean(""); // false
Boolean({}); // true
!Boolean(""); // true
Copy the code
+ conversion rule
+ converts variables to numbers
+"10"; / / 10
+"asd"; // NaN
Copy the code
Quickly convert time to timestamp
+new Date(a);/ / 1599039501529
Copy the code
== conversion rule
Type the same
It compares addresses in heap memory
1= =1; // true
"1"= ="1"; // true{} = = {};// false
Copy the code
Different types
As long as null == undefined is true and null/undefined is not equal to any other data type
null= =undefined; // true
undefined= ="1"; // false
null= ="1"; // false
Copy the code
If the data types on both sides of the == sign are different, the data types on both sides are converted to numbers for comparison