Type conversion in javascript
Javascript is a weakly typed language, and variables are type independent, so sometimes we need to do type conversions
Number conversion (number)
Two methods:
ParseFloat, parseInt, parseInt, parseFloat, parseInt, parseFloat, parseInt, parseInt, parseFloat, parseIntCopy the code
number
The reference type is converted to a string (toString) method before the string is converted to a number
String => number: Non-valid number is converted to string Boolean value => Number: 1 or 0 NULL => number: 0; I therefore pay, therefore I am 5. Therefore, I pay, therefore I am 6. Therefore, I pay, therefore I am 6. // 10 Number('10'); // 10 Number(null); // 0 Number(''); // 0 Number(true); // 1 Number(false); // 0 Number([]); / / 0 Number ([1, 2]); // NaN Number('10a'); // NaN Number(undefined); // NaNCopy the code
Parseint () parsefloat ([va], [base]) parseint () parsefloat ([va], [base]) parseint () parsefloat ([va],]) parsefloat ([va],])
If it is not a string, convert it to a string before using this method
Let STR = '12.5px' parseInt(STR)// 12 parseFloat(STR)// 12.5 parseFloat(true)// NaNCopy the code
IsNaN determines the number type:
Return false if the current type is numeric, true otherwise
String conversion (string)
The primitive type, using the toString method () is what did it look like before enclosing quotes around it
Number => String: Enclose quotation marks. NaN => String: 'NaN'. True => String: 'true'. Null => String: 'null' (browser will error (forbid you to use) -- usually can be converted) undefined => string: 'undefined' (browser will error (forbid you to use) -- usually can be converted) Object => string: '[object object]'.Copy the code
Ordinary objects into the results for “[object object]”, because the object. The prototype. The toString method is not converted to a string, but used to detect the data type.
String(123); // "123" String(true); // "true" String(null); // "null" String(undefined); / / "undefined" (error) String ([1, 2, 3]) / / "1, 2, 3" String ({}); // "[object Object]"Copy the code
Boolean type conversion (Boolean)
1.
2: underfined,
3: NaN,
4: null,
5: false,
6:0,
The above six values are false when converted to Booleans, and the others are true
Boolean('') // false
Boolean(undefined) // false
Boolean(null) // false
Boolean(NaN) // false
Boolean(false) // false
Boolean(0) // false
Boolean({}) // true
Boolean([]) // true
Copy the code
4. Primitive type conversion
There are two cases of converting a primitive type: to a string type or another primitive type.
If it is already a primitive type, no further conversion is required.
If you convert to a string, the toString() method in the built-in function is called.
If it is any other primitive type, the valueOf() method in the built-in function is called.
If not the original type is returned, the toString() method is continued.
If the original type has not been returned, an error is reported.