JavaScript Data Type Conversion
Foreword
JavaScript is a dynamic language. The so-called dynamic language can be temporarily understood as everything in the language is uncertain. For example, a variable, which is an integer at this moment, may become a string at the next moment. Although the data type of the variable is indeterminate, various operators have requirements on the data type. If the operator finds that the type of the operator is not as expected, it automatically converts the type.
This article mainly introduces data type coercion and automatic conversion, and automatic conversion is based on coercion. Coercion mainly refers to using the three functions of Number, String and Boolean to manually convert various types of values and distributions into numbers, strings or Boolean values .
1. Forced conversion
1. Convert other data types to String
Method 1: toString() method
- Call the toString() method of the converted data type, this method will not affect the original variable, it will return the result of the conversion, but note: the two values of null and undefined do not have toString, if you call their methods, an error will be reported .
var a = 123
a.toString()//"123"
var b = null;
b.toString()//"Error"
var c = undefined
c.toString()//"Error"
- Using the base mode of the toString() method of the Number type, you can output numbers in different bases, such as binary base 2, octal base 8, and hexadecimal base 16
var iNum = 10;
alert(iNum.toString(2)); // output "1010"
alert(iNum.toString(8)); //output "12"
alert(iNum.toString(16)); // output "A"
Method 2: String() function
When using the String() function for type conversion, the toString() method is actually called for Number and Boolean,
but for null and undefined, the toString() method will not be called, it will directly convert null to "null" , convert undefined directly to "undefined"
var a = null
String(a)//"null"
var b = undefined
String(b)//"undefined"
If the parameter of the String method is an object, it returns a type string; if it is an array, it returns the string form of the array.
String({a: 1}) // "[object Object]"
String([1, 2, 3]) // "1,2,3"
2. Convert other data types to Number
Method 1: Use the Number() function
The following is divided into two cases to discuss, one is that the parameter is a value of primitive type, and the other is that the parameter is an object
(1) Primitive type value
① String to Number
Ⅰ If it is a string of pure numbers, convert it directly to a number
Ⅱ If the string contains non-numeric content, it will be converted to NaN
Ⅲ If the string is an empty string or a string full of spaces, convert to 0
Number('324') // 324
Number('324abc') // NaN
Number('') // 0
② Boolean value to number: true to 1, false to 0
Number(true) // 1
Number(false) // 0
③ undefined to number: convert to NaN
Number(undefined) // NaN
④ null to digital: convert to 0
Number(null) // 0
⑤Number() accepts a value as a parameter. At this time, it can recognize both negative hexadecimal and octal starting with 0. The return value is always a decimal value.
Number(3.15); //3.15
Number(023); //19
Number(0x12); //18
Number(-0x12); //-18
(2) Object
The simple rule is that when the argument to the Number method is an object, it will return NaN, unless it is an array containing a single numeric value.
Number({a: 1}) // NaN
Number([1, 2, 3]) // NaN
Number([5]) // 5
Method 2: parseInt() & parseFloat()
This method is specially used to deal with strings. parseInt() converts a string to an integer, which can take out the valid integer content in a string and convert it to Number. parseFloat() converts a string to a float. parseFloat() is similar to parseInt(), except that it can obtain valid decimals.
console.log(parseInt('.21')); //NaN
console.log(parseInt("10.3")); //10
console.log(parseFloat('.21')); //0.21
console.log(parseFloat('.d1')); //NaN
console.log(parseFloat("10.11.33")); //10.11
console.log(parseFloat("4.3years")); //4.3
console.log(parseFloat("He40.3")); //NaN
parseInt() converts the value in decimal by default when there is no second parameter. When there is a second parameter, it converts the value with the second parameter as the base, and returns NaN if the base is incorrect
console.log(parseInt("13")); //13
console.log(parseInt("11",2)); //3
console.log(parseInt("17",8)); //15
console.log(parseInt("1f",16)); //31
The difference between the two: The Number function converts a string to a numeric value, which is much stricter than the parseInt function. Basically, as long as there is one character that cannot be converted to a number, the entire string will be converted to NaN.
parseInt('42 cats') // 42
Number('42 cats') // NaN
In the above code, parseInt parses characters one by one, and the Number function converts the type of the string as a whole.
Also, the handling of empty strings is different
Number(" "); //0
parseInt(" "); //NaN
3. Convert other data types to Boolean
Its conversion rules are relatively simple: only empty strings (""), null, undefined, +0, -0, and NaN are converted to boolean types, and the others are true. true, even the boolean object new Boolean(false) corresponding to false is true
Boolean(undefined) // false
Boolean(null) // false
Boolean(0) // false
Boolean(NaN) // false
Boolean('') // false
Boolean({}) // true
Boolean([]) // true
Boolean(new Boolean(false)) // true
2. Automatic conversion
In the following three cases, JavaScript will automatically convert the data type, that is, the conversion is done automatically and is not visible to the user.
1. Automatic conversion to boolean
Where JavaScript encounters an expected boolean value (such as the conditional part of an if statement), it automatically converts non-boolean arguments to boolean values. The Boolean function is automatically called internally by the system.
if ('abc') {
console.log('hello')
} // "hello"
2. Automatically convert to numeric values
When the arithmetic operator (+ - * /) operates on values that are not of type Number, it converts these values to Number, and then operates on them, except for the addition of strings.
true + 1 // 2
2 + null // 2
undefined + 1 // NaN
2 + NaN // NaN Any operation with NaN results in NaN
'5' - '2' // 3
'5' * '2' // 10
true - 1 // 0
'1' - 1 // 0
'5' * [] // 0
false / '5' // 0
'abc' - 1 // NaN
Unary operators also convert operators to numbers.
+'abc' // NaN
-'abc' // NaN
+true // 1
-false // 0
3. Automatically convert to string
The automatic conversion of strings mainly occurs during the addition of strings. When one value is a string and the other is a non-string, the latter is converted to a string.
'5' + 1 // '51'
'5' + true // "5true"
'5' + false // "5false"
'5' + {} // "5[object Object]"
'5' + [] // "5"
'5' + function (){} // "5function (){}"
'5' + undefined // "5undefined"
'5' + null // "5null"
3. Summary
1. Various cases of forced conversion
2. Various situations of automatic conversion
- Only empty strings (""), null, undefined, +0, -0 and NaN converted to boolean are false, others are true
- Except for the addition operator (+), which may convert the operator to a string, other operators will automatically convert the operator to a number. Unary operators also convert operators to numbers.
- The automatic conversion of strings mainly occurs during the addition of strings.