Take writing as a hobby and keep doing it. Once this is a small hope, now has been gradually in the realization.

To make a long story short, since it is a technical article, I will not send so many regrets. Next, let’s enter the main topic of today.

Today I’m going to talk about implicit conversions in JavaScript. I believe many partners have been troubled by it, whether in the development process or in the interview process. I hope today’s sharing can bring you a different understanding. It’ll help you not worry about it later.

1. Basic data types

As we all know, there are seven data types in javascript. Object, Null, Undefined, String, Number, Boolean, Symbol. These are things that we touch all the time, every day, during normal development, and we won’t go over them here.

2. Cast type

In the usual use process, we will encounter a lot of inconsistent data type problems, similarly, forced to convert different data types to the same data type is also very normal operation; Next, let’s look at what the cast methods are:

2.1 Character String -> Number

1. parseInt
parseInt('123') / / 123
parseInt('123abc') / / 123
parseInt('12.3 ABC') / / 12
parseInt('abc123') // NaN
Copy the code

Explanation:

This method only converts the string that begins with a number until it is not a number, and then ends with NaN if the string does not begin with a number

2. parseFloat
parseFloat('123') / / 123
parseFloat('12.3 ABC') / / 12.3
parseFloat('1.2.3 ABC') / / 1.2
parseFloat('abc1.23') // NaN
Copy the code

Explanation:

Same rule as parseInt, except that only one decimal point can be converted, and if multiple decimal points, only one decimal point can be converted.

3. Number
Number('123') / / 123
Number('12.3 ABC') // NaN
Number('1.2.3 ABC') // NaN
Number('abc1.23') // NaN
Copy the code

Explanation:

This method converts only all-numeric strings if the string is not all-numeric. As ABC ‘12.3’, ‘1.2.3 ABC’, ‘abc1.23………………… Is converted to NaN

4. A computation

The use of bit operations is so rare on the front end that many front end people are not clear about how to use them. Now let’s see, how can we use bitwise operations to convert a string to a number

There are mainly the following operations to do the conversion

  • ~
  • <<Shift to the left
  • >>Moves to the right

We’re not going to describe how bitwise operations actually work, but how do we use them to convert strings to numbers

~ ~'123'    // 123 (here are two wavy lines)
'123' << 0 / / 123
'123' >> 0 / / 123
Copy the code

Explanation:

Use the same method as Number. Are strings that can only convert to full numbers. For strings that are not all digits, ~ is converted to NaN, and the other two are converted to 0

2.2 Numbers -> Strings

1. Use+Operator.
' ' + 123 / / '123'
Copy the code
2. UsetoStringmethods
let num = 123
num.toString() / / '123'
Copy the code
Use 3.Stringmethods
let num = 123
String(num) / / '123'
Copy the code

2.3 Convert to a Boolean value

1.!!!!! Methods. A double negative is an affirmative. Use double non to get the Boolean value converted from the original value.
let num = 123!!!!! num// true

let str = '123'!!!!! str// true
Copy the code
2. Booleanmethods
let num = 123
let str = '123'
Boolean(123) // true
Boolean('123') // true
Copy the code

Note:

False in JavaScript:

  • "'," "An empty string
  • 0digital0
  • undefined
  • null
  • NaN
  • false

3. Implicit type conversion

3.1 Operations that trigger implicit type conversions

  • arithmeticThe +, -, *, /
  • To compare> < >= <= ==.
    • Note:= = =Implicit type conversions are not triggered.
  • judgeif, while

3.2 toStringvalueOfinstructions

These two methods convert complex data types to raw value output.

1. CallvalueOfMethods after
  • String, Number, BooleanReturns a string value, a numeric value, and a Boolean value.
  • Object, Array, FunctionIt returns itself
  • DateReturns the value of milliseconds from the beginning to the present
2. CalltoStringMethods after
  • String, Number, BooleanReturns a value that is not a string
  • ObjectReturns the[object Object]
  • ArrayAn empty string is returned. Because in theArrayOverride this method in
  • functionReturns the string of the function itself
  • DateThis returns the time, not the number of milliseconds

Note:

Is called first when the original value (toPrimitive) is obtainedvalueOfMethod, if it does not return a primitive value (that is, a primitive data type), then the call continuestoStringMethods. If it’s not the original value. An error is reported.

3.3 Example Analysis

Please try to answer the questions below before viewing the parse

/ / array[] = =! []/ / 1[] [] = =/ / 2[] = =false / / 3[] = =true  / / 4
[1] = =1    / / 5[] = =0     / / 6
[12] < [13] / / 7

/ / object= = {} {}/ / 8{} = =! {}/ / 9
{} != {}    / / 10

/ / version
[] + {}     / / 11
{} + []     / / 12
{} + {}     / / 13
[] + []     / / 14
{} + 1      / / 15
1 + {}      / / 16
Copy the code

Here’s the answer. Ready or not

1. [] = =! []step
// Add! [] Convert to original value -->! [] to false[] = =false
// Converts [] to the original value [].valueof () returns itself, continuing toString returns an empty string
' '= =false
// Convert an empty string to a Boolean value. The empty string is false
false= =false
// Get the result [] ==! [] --> true
Copy the code
2. [] [] = =
We're comparing addresses, and the addresses of the two arrays are different. The results forfalse
Copy the code
3. [] == false

[] ==! []

4. [] == true

[] ==! []

5. [1] = = 1
// Get the original value [1], call valueOf to return itself, continue toString to return '1'
1= =1
[1] == 1 --> true
Copy the code
6. [] = = 0
// get [] the original value, call valueOf to return itself, continue toString to return ' '' '= =0
// Convert an empty string to a number '' --> 0
0= =0
[] == 0 -> true
Copy the code
7. Box [12] [13]
// Convert left and right to the original values
'12' < '13'
// get the result true
Copy the code
8. = = {} {}

With [] = = []

9. {} = =! {}

With [] = =! [] The difference is that {} is converted to [object object] as a string. So the result is the same as [] ==! [] instead

10. {}! = = {}

Same as {} == {}

11. [] + {}
// Get both the original values.
' ' + '[object Object]' = '[object Object]'
Copy the code
12. {} + []

If the value on the right is not worth a dictionary format, the brace is treated as an empty block. That is, the expression can be converted to the following expression + [], which is then converted to an empty string and then to a number, yielding the number 0.

So: {} + [] == 0

13. {} + {}

Do object processing on both sides, get the original value

'[object Object]' + '[object Object]' = '[object Object][object Object]'
Copy the code
14. [] + []

Gets the original left and right values, all converted to an empty string. And then we do string concatenation

' ' + ' ' = ' '
Copy the code
15. {} + 1

Same as {} + [], can be deformed into + 1

16. 1 + {}

Obtain the original value of {} on the right to obtain ‘[object object]’, which can be transformed into

1 + '[object Object]' = '1[object Object]'
Copy the code

4. Supplementary points

  • NaNIs not equal to any value, including itself.
  • There areundefinedIn any of the four operations, the result is zeroNaN
  • Boolean valuetrueWhen converting numbers, convert to1falseIs when converted to a number0
  • Strings compare sizes, but really compare character encodings. Such as:a > A = 97 > 65 = true

Well, today’s article is to share here, did not write too much concept, just let you look at the results of the actual operation. A general rule, know the actual operation of the process, and then encounter similar problems with ease.