Detailed explanation of JavaScript data type conversion (recommended)

Time:2021-10-17

JS data type

In JavaScript language, data types are divided into two categories: basic data types and complex data types

Basic data types include:

  • number
  • string
  • boolean
  • null
  • undefined
  • symbol
  • bigint

Complex data types include:

  • Standard common object: object
  • Standard special objects: array, regexp, date, math, error
  • Non standard special objects: number, string, Boolean
  • Callable / executable object “function”: function

Conversion between types

Type conversion can be divided into two types: implicit type conversion and explicit type conversion.

Explicit type casting refers to when developers write appropriate code to convert between types, such as number (value).

Implicit type conversion means that when operators are used for different types of values, values can be automatically converted between types, such as 0 = = null

There are only three types of transformations in JS:

  • Convert to number type: number() / parsefloat() / parseint()
  • Convert to string type: string() / tostring()
  • Convert to boolean type: Boolean ()

The logic of type conversion will only convert to one of the above three types regardless of the original type and object type. So you just need to figure out what kind of scene you should turn into

Convert to Boolean

Explicit: the Boolean () method can be used to explicitly convert values to Booleans.

Implicit: implicit type conversion is usually triggered when there is a logical judgment or a logical operator (| & &!).

Boolean type conversion can only have true or false results. Except that the five values of “0 / Nan / empty string / null / undefined” are false, the rest are true

Convert to string

Explicit: the string () method can be used to explicitly convert a value to a string.


String([1,2,3])    //"1,2,3"
String({})    //"[object Object]"

Implicit conversion is usually triggered when there is a + operator and one operand is of type string.

“+” represents string splicing. If the following conditions exist, the conversion will be triggered

  • If there are two sides and one side is a string, it will become string splicing;
  • There are two sides, one side is the object

1 + {}     //"1[object Object]"
NaN + {} //"NaN[object Object]"

Convert to number

Explicit: the number () method can be used to explicitly convert a value to a number type.

Convert string to number: the empty string becomes 0. If any non valid numeric character appears, the result is Nan


Number("")           //0
Number("10px")       //NaN
Number("10")         //10

Convert Boolean to number


Number(true)         //1
Number(false)        //0

Null and undefined are converted to numbers


Number(null)         //0
Number(undefined)    //NaN

Symbol cannot be converted to a number, and an error will be reported: uncaught typeerror: cannot convert a symbol value to a number

Bigint removes “n”


Number(12312412321312312n)     //12312412321312312

To convert an object to a number, follow the steps below

First call the symbol.toprimitive method of the object. If this method does not exist

Then call valueof of the object to obtain the original value. If the obtained value is not the original value

Then call the toString of the object to change it into a string

Finally, the string is converted to a number based on the number () method

let obj ={
    name:'xxx'
}
Console.log (obj-10) // mathematical operation: first implicitly convert obj to a number, and then perform the operation
//Operating mechanism
obj[Symbol.toPrimitive] //undifined 
obj.valueof() // {name:xxx}
obj.toString() // [object object]
Number ("[object object]") // NaN
NaN-10 // NaN 
obj+10 //"[object object]10"

Implicit: the implicit type conversion of number is complex because it can be triggered in many cases.

  • Comparison operation (>, <, < =, > =)
  • Bitwise operation (| & ^ ~)
  • Arithmetic operation (- + * /%). Note: when any operand of + operation is of string type, the implicit conversion of number type will not be triggered
  • Unary + operation

Operator = = implicit conversion rules on both sides

If the data types on both sides are different, you need to change to the same type first, and then compare them. Pay attention to the following situations:

You can refer to this diagram, such as object and Boolean comparison,

  • Object = > string = > value
  • Boolean = > value.

Object = = string


[1,2,3]=='1,2,3'              //true
[1,2,3][Symbol.toPrimitive]   //undefined
[1,2,3].valueOf()             //[1, 2, 3]
[1,2,3].toString()            //"1,2,3"

null/undefined

null==undefined      //true 
Null = = = undefined // false no implicit type conversion will occur

Note: null / undefined is not equal to any other value

Object = = object

The heap memory addresses are compared, and the same addresses are equal

{} = = {} // false because the address is compared

NaN

In addition to the above, as long as the types on both sides are inconsistent, the rest are converted to numbers and then compared

Situations requiring attention

{} + [] === 0               // true
[] + {} === 0               // false

[] + {}  = "[object Object]"
{} + []  = 0
/**
  *For the compiler, the code block does not return any values
  *Then + [] becomes a forced number conversion process
  *[] becomes' 'through toprimitive, and finally' 'is converted to 0 through ToNumber operation
  **/

Ending exercise

let result = 100 + true + 21.2 + null + undefined + “Tencent” + [] + null + 9 + false;

What is the result of result?

1. First, 100 + true
+There is a number type on both sides of the connector. True turns number to 1. The result is 101
2.101 + 21.2
+Both sides of the connector are of number type. The result of addition is 122.2
3.122.2 + null
+There is a number type on both sides of the connector. Null is converted to number 0. The addition operation is carried out, and the result is 122.2
4.122.2 + undefined
+There are number types on both sides of the connector. Undefined turns number to Nan. Nan and any data type are calculated as Nan. The result is Nan
5.NaN + “Tencent”
+There is a string type on both sides of the connector. Nan is converted to “Nan”, and the string is spliced. The result is: “nantencent”
6.”NaNTencent” + []
+There is a string type on both sides of the connector, [] turns string to ”, splices the string, and the result is: “nantencent”
7.”NaNTencent” + null
+There is a string type on both sides of the connector. Null is converted to “null” for string splicing. The result is: “nantencentnull”
8.”NaNTencentnull” + 9
+There is a string type in the connector, 9 to string is “9”, and the string splicing result is: “nantencentnull9”
9.”NaNTencentnull9″ + false
+String type exists in the connector, false is converted to “false”, string splicing is performed, and the result is: “nantencentnull9false”

summary

This is the end of this article on JavaScript data type conversion. For more information about JS data type conversion, please search previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!