JavaScript data type conversion

Time:2021-10-24

preface

JavaScript is a dynamic language. The so-called dynamic language can be temporarily understood as that everything in the language is uncertain. For example, a variable, which is an integer at one time, may become a string at the next time. Although the data type of variables is uncertain, various operators have requirements for data types. If the operator finds that the type of the operator does not match the expectation, it will automatically convert the type.

This paper mainly introduces data type coercion and automatic conversion. Automatic conversion is based on coercion.Coercion mainly refers to the manual conversion of various types of values into numbers, strings or boolean values using number, string and Boolean functions

1、 Force conversion

1. Other data types are converted 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 conversion result,But note: null and undefined values do not have toString. If their methods are called, an error will be reported
var a = 123
a.toString()//"123"
var b = null;
b. Tostring() / "error reporting"
var c = undefined
c. Tostring() / "error reporting"
  • Using the base mode of toString () method of number type, you can output numbers with different bases. For example, the base of binary is 2, the base of octal is 8, and the base of hexadecimal is 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 the string () function is used for cast type conversion, the number and Boolean are actually the toString () methods called,
    However, for null and undefined, the toString () method will not be called. It will directly convert null to “null” and undefined 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, the string form of the array is returned.
String({a: 1}) // "[object Object]"
String([1, 2, 3]) // "1,2,3"

2. Other data types are converted to number

Method 1: use the number() function

The following discussion is divided into two cases: one is that the parameter is the value of the original type, and the other is that the parameter is an object

(1) Original type value

① String to number

If I is a pure numeric string, it is directly converted to a number

II. If there is non numeric content in the string, it will be converted to Nan

III. If the string is an empty string or a string full of spaces, it is converted 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: converted to Nan

Number(undefined) // NaN

④ Null to number: 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 parameter of the number method is an object, Nan will be returned, unless it is an array containing a single 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 then convert it to number. Parsefloat() converts a string to a floating point number. 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 in cardinality based on the second parameter. If the cardinality is wrong, Nan is returned

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 into a value, which is much more strict than the parseInt function. Basically, as long as one character cannot be converted to a numeric value, the whole string will be converted to Nan.

parseInt('42 cats') // 42
Number('42 cats') // NaN

In the above code, parseInt parses characters one by one, while the number function converts the type of string as a whole.
In addition, the processing of empty strings is also different

Number("   ");     //0    
parseInt("   ");   //NaN

3. Other data types are converted to Boolean

Its conversion rules are relatively simple:Only empty string (“”), null, undefined, + 0, – 0 and Nan are converted to Booleans as false, others are true, empty arrays and empty objects are converted to Booleans as true, and 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 completed automatically and not visible to the user.

1. Automatically convert to Boolean

JavaScript automatically converts non Boolean parameters to Boolean values where they are expected to be Boolean values (such as the conditional part of an IF statement). The system will automatically call the Boolean function.

if ('abc') {
  console.log('hello')
}  // "hello"

2. Automatic conversion to numerical value

When the arithmetic operator (+ – * /) operates with values of non number type, it converts these values to number, and then performs the operation, except for the addition of string

true + 1 // 2
2 + null // 2
undefined + 1 // NaN
2 + Nan // Nan is required for any value of 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 string mainly occurs in the addition operation of string. When one value is a string and the other value 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 situations of forced conversion

2. Various situations of automatic conversion

  • Only empty string (“”), null, undefined, + 0, – 0 and Nan are converted to Boolean, which is false, and others are true
  • Except that the addition operator (+) may convert the operator to a string, other operators will automatically convert the operator to a numeric value. Unary operators also convert operators to numbers.
  • The automatic conversion of string mainly occurs in the addition operation of string.

Postscript

If you need front-end guidance or front-end information, please contact me and thank you for your support.

WECHAT:xzsj07
Learn more

Note: please indicate the source.

Author: boating in the waves
Link:JavaScript data type conversion
Source: GitHub
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, and for non-commercial reprint, please indicate the source.

Recommended Today

SQL exercise 20 – Modeling & Reporting

This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress:https://github.com/nino-laiqiu/TiTanI recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]