This is the fourth day of my participation in the August Text Challenge.More challenges in August

Type Conversion (2)

01. Object conversion

  • In the absence of toString() and valueOf() methods

    • Object converted to a string, returns[object Object]
    • Object converted to a value, returnsNaN

  • A valueOf or toString method can be called when an object is converted to a primitive type, if a method is available:

    1. If you have a valueOf() method

      • If it returns a primitive type value (primitive type value), it returns it directly

      • If the value returned is not a primitive type, the toString() method is called

    2. If there is no valueOf() method

      • Will calltoString()methods
    3. If you have toString()

      • If a value of primitive type is returned, it is returned directly

      • If a value other than a primitive type is returned, the object cannot be converted to a string, and finally an error is thrown indicating that the object cannot be converted to a string

    Note the order:

    • When working with objects, and, in useNumber()When converted to a value
      • Follow first callvalueOf()Call again,toString()
    • In the use ofString()Convert to string
      • Follow first calltoString()Call again,valueOf()
let obj = {
    a: 1.valueOf(){
        console.log('valueOf')
        return[]},toString(){
        console.log('toString')
        return 2}}// 1. Perform operations using objects
console.log(obj + 1) 
// First call valueof(), which returns [], not a primitive type value
// Continue calling toString(), which returns 2, a numeric type
// Calculate 2 + 1 = 3
// Result -- prints: valueof toString; Returns: 3


// 2. Convert to a Number using Number()
console.log(Number(obj)) 
// First call valueof(), which returns [], not a primitive type value
// Continue calling toString(), which returns 2, a numeric type
// Result -- prints: valueof toString; Returns: 2


// 3. Convert to a String using String()
console.log(String(obj))
// Call toString() first, which returns 2, a numeric type
// Result -- prints: toString; Returns: 2


// 4. Call the corresponding method directly
console.log(obj.toString()) // Print: toString; Returns: 2
console.log(obj.valueOf()) // Print: valueOf; Returns: []

Copy the code

  • Both of these methods can be overridden

    • Alternatively, you can override this method on the object:[Symbol.toPrimitive], this method has the highest precedence when converting primitive types
    let obj = {    
        num: 1.// Has the highest priority
        [Symbol.toPrimitive](){
            return 3    
        },
        valueOf(){
            return 2    
        },
        toString(){        
            return '1'}}// [symbol.toprimitive] has the highest priority, so return 3
    console.log(obj + 0) / / 3
    console.log(obj + '0') / / '30'
    
    // If none of these three methods are available, return [object object]
    console.log(obj + 0) // [object Object]0
    console.log(obj - 0) // NaN
    
    Copy the code
  • In particular, some operations can be performed during transformation

    let obj = {    
        num: 1[Symbol.toPrimitive]()
        {       
            return this.num++    
        }
    }
    console.log(obj == 1 && obj == 2 && obj == 3) // true
    
    Copy the code

02. Array conversion

  • In the case of arrays, when converting to primitive types

    • If is an empty array: converts the string to' ', is converted to the numerical type0
    • If there is only one value, the value is converted to the corresponding string and converted to a numeric value
    • If there are multiple values: can be converted to a string, but not to a numeric type

    But you can also override its toString, toPrimitive methods (changed by direct assignment)

    let arr = [1.2.3]
    arr[Symbol.toPrimitive] = arr.shift // arr.shift() pops up the first value of the array
    arr.toString = arr.pop
    
    // [Symbol. ToPrimitive] has a higher priority than toString
    console.log(arr == 1 && arr == 2 && arr == 3) // true
    
    Copy the code
  • Alternatively, arrays can be converted to strings using their own methods

    • usejoin()Method can concatenate strings. The default separator is., you can also customize the delimiter
    let arr = ['a'.'b'.'c']
    arr.join() // a,b,c
    arr.join(The '-') // a-b-c
    
    Copy the code

03. Operator conversion

  • Concept: through operator conversion, such as A == B, A > B

  • Rules:

    • Except when a string is compared to an object, the object needs to be converted to a string for comparison
    • Everything else, as long as the type is different, is converted to a numeric type for comparison
  • Example:

    • Number == string: Converts strings to numbers for comparison
    • Number == Boolean: Converts booleans to numbers for comparison
    • Number == object: Converts an object to a string and then to a number for comparison
    • String == Boolean: are converted to numbers for comparison
    • Object == Boolean: are converted to numbers for comparison
    • Object == string: That object is converted to a string for comparison
  • In particular, null and undefined do not perform type conversions for equality with other data

    • But in relational operations (greater than, less than,…) , will perform type conversion

    • null == undefined

  • [] ==! []

    1. First determine whether the type is consistent

      • On the left is[], object type
      • On the right is the! [], Boolean type,! [] == false

      If the types are inconsistent, both are converted to numeric types for comparison

    2. Converts a Boolean value to type Number

      • Number(false) == 0
    3. Converts the value of the object type to type Number

      • First converted to a string:[].toString == ''
      • Convert the string to a value:Number('') == 0
    4. The final comparison

      • 0 = = 0
      • So the final result is zerotrue

04. Operator conversion

  • Only when one side of an addition is a string will the other be converted to a string

    • And addition triggers three type conversions
      • Converts the value to the original value
      • Convert to numbers
      • Convert to string
  • Digital situation

    Number + number = number

    Boolean + Boolean = number

    Number + Boolean = number

    Number +Null= number

console.log(1 + '1') / / 11
console.log(1 + null) / / 1

console.log([] + []) / /"
console.log([] + {}) // '[object Object]'

Copy the code

Console. log(! +[] +[] +! [])

  • Although there are three + signs, there is no data before the first +

    • So it is an implicit conversion of numeric type, that is:+ [] = = 0
    • So:! + [] = =! 0 == true
  • So the last one! [] is a Boolean value

    • According to Boolean conversion rules, except for thatSeven valuesAnd everything else is converted totrue
    • So here! [] = =! true == false
  • The final expression is console.log(true + [] + false).

    • OK, no numeric type, result is a string,[] = = ' '
    • So the end result is:'truefalse'

I front-end side dish chicken, if there is wrong, please forgive