Implicit conversion rules

1.ToString, ToNumber, ToBoolean, ToPrimitive

First, take a look at the basic rules for converting between JS data types, such as numbers, strings, Bools, objects, and arrays.

1.1 the ToString

Note the difference between the toString method, which converts other types to character-to-character operations.

Here we discuss the rules for null, undefined, Booleans, plain objects, and arrays converted to strings

  • Null: Converts to'null'
  • Undefined: converts to'undefined'
  • Boolean type:trueandfalseConvert to'true'and'false'
  • Number type: a string converted to a number,11convert'11'.1e21convert'1e+21'
  • Plain objects: Conversion strings are equivalent to direct callsObject.prototype.toString()To return to'[object Object]'
  • Array type: equivalent to callArray.prototype.join()Method,[' 1 ', '2', '3']Converted to'1, 2, 3'.[]To an empty string in an arraynull,undefinedWill be treated as an empty string
String(null) // 'null'
String(undefined) // 'undefined'
String(11) / / '11'
String(1e21) // '1e+21'
String({}) // '[object Object]'
String([]) / /"
String([' '.null.undefined]) / / ', '
Copy the code

Note: The rule mentioned above is that by default, modifying the default toString() will affect the result

1.2 ToNumber

ToNumber refers to operations that convert other types to numeric types

  • Null: Converts to0
  • Undefined: converts toNaN
  • Boolean type:trueconvert1.falseconvert0
  • String type: If it is a pure number, it is converted to the corresponding number, and an empty string is converted to0, others are treated as conversion failure, andNaN
  • Object type: The array is first converted to its original type, i.eToPrimitive, and then the converted prototype type is processed according to the above rules,ToPrimitiveThis will be described below
Number(null) / / 0
Number(undefined) // NaN
Number('123') / / 123
Number(' ') / / 0
Number('123e') // NaN
Number([]) / / 0
Number(['1'.'2']) // NaN
Number({}) // NaN
Copy the code

1.3 ToBoolean

ToNumber refers to operations that convert other types to Booleans

The only false values in js are null, undefined, 0, ”, NaN, and the rest are true

Boolean(null) // false
Boolean(undefined) // false
Boolean(0) // false
Boolean(' ') // false
Boolean(NaN) // false
Boolean([]) // true
Boolean({}) // true
Copy the code

1.4 ToPrimitive

ToPrimitive is an operation that converts an object type (plain object, array) to a primitive type

  • When an object type needs to be converted to its original type, the object is looked up firstvalueOfMethod, ifvalueOfReturns a value of the original type, thenToPrimitiveI’m going to return that result.
  • ifvalueOfReturn not the original type, orvalueOfMethod does not exist, call the object’stoStringMethods, which follow the objectToStringRule, then usetoStringReturn value asToPrimitiveThe return value of.
  • ifvalueOfandtoStringNone return a value of the original type, then an exception is thrown.
Number([]) / / 0
Number(['1']) / / 1
Copy the code
const obj2 = {
    valueOf(){
        return '11';
    },
    toString(){
        return '12'; }}Number(obj2) / / 11
Copy the code
const obj3 = {
    toString(){
        return '123'; }}Number(obj3) / / 123
Copy the code
const obj4 = {
    toString(){
        return{}; }}Number(obj4) // Uncaught TypeError: Cannot convert object to primitive value
Copy the code

2. Implicit conversion rules for loose equality (==) comparisons

The difference between loose equality (==) and strict equality (===) is that loose equality is implicitly converted in comparison. Now let’s look at the conversion rules for different cases.

2.1 Comparison of Boolean types and other types

  • As long asBoolean typeParticipate in the comparison, theBoolean typeThe value of is first converted toNumeric types
  • According to theBoolean typetheToNumberThe rules,trueconvert1.falseconvert0
false= =0 // true
true= =1 // true
true= =2 // false
Copy the code

2.2 Comparison between digit type and Character conversion Type

  • whenNumeric typesandString typeWhen you compare,String typeWill be converted toNumeric types
  • According to the stringToNumberRule, if the string is in pure numeric form, it is converted to the corresponding number, and empty characters are converted to0Otherwise, the conversion will be processed as conversion failureNaN
  0= =' ' // true
  1= ='1' // true
  1e21= ='1e21' // true
  Infinity= ='Infinity' // true
  true= ='1' // true
  false= ='0' // true
  false= =' ' // true
Copy the code

2.3 Comparison between Object Types and original Types

  • whenObject typeandThe original typeWhen I do an equality comparison,Object typeWill be in accordance with theToPrimitiveRule conversion toThe original type
  '[object Object]'= = {}// true
  '1, 2, 3'= = [1.2.3] // true
  [2] = =2 // true
  [null] = =0 // true
  [undefined] = =0 // true[] = =0 // true
Copy the code

2.4 Comparison of NULL, undefined, and other types

  • nullandundefinedLoose equality is true, everything else is false
  null= =undefined // true
  null= =false // false
  undefined= =false // false
Copy the code

3. Classic interview questions

Define a variable a such that the following expression results in true

  a == 1 && a == 2 && a == 3
Copy the code

Object each time and primitive types do = = comparison, will conduct a ToPrimitive operation, that whether we can define an object contains the valueOf or toString method, and then by a value of cumulative?

const a = {
    value: 1.valueOf(){
        return this.value++;
    }
}
a == 1 && a == 2 && a == 3 // true
Copy the code