Convert to a numeric type

Common application scenarios

  • Mathematical operations
  • The = = comparison
  • Manual switch

Mathematical operations

Everything except “+” is math, plus is not just math, it’s string concatenation

  • “+” has values on both sides, string or object on one side, string concatenation
    • Principle: the call Object. The prototype. The toString method
    • Only pure objects can be converted to [object object]
      • Originally want to {} to digital, but Symbol. ToPrimitive/the valueOf/toString, transferred to the toString is a string, at that moment, in the one side into a string, string concatenation
    • A special case
      • {}+10–> 10: {} is considered a code block (ES6 block-level context), only +10 is actually performed, so the final result is 10
      • ({}+10) –> ‘[object object]10’ : wrap the contents in parentheses and treat them as a whole
      • There’s only one side / ++ +x/ x++, it’s all math
        • +’10’ –> 10: Number type
        • 10+(++X) : First add X to 1, then add to 10
        • 10+(X++) : Sums 10 and adds X to 1

X ++ == x+=1 == x=x+1?

Analysis of the

  • let x = ’10’; console.log( ++x );
    • One side is a math operation, which changes to a number of type 10 and then increments by 1. The result is assigned to x as 11
  • console.log( x+=1 );
    • x+=1 –> x=x+1 –> ’10’+1–>’101′

The object type is converted to a numeric type

The internal mechanism

  • First check the object’s Symbol. ToPrimitive property to get the original value
    • Symbol.toprimitive (hint) : Hint detects the conversion type implicitly specified by the browser: ‘number’/’string’/’default’
  • Without this attribute, continued to call it the valueOf (), and access to the original value (number/string/Boolean/null/undefined symbol/bigint)
  • If the value is not the original value, the call toString() continues to convert to a string
  • The string is then converted to a Number based on Number(STR)

The other types are converted to number

Number type conversion rule

Number( undefined) :NaN
Number( null) : +0
Number( true) :1
Number( false) : +0	
Number(number) : Returns parameter "No conversion required"Number(Symbol type) : Throws an exception of type error "Symbol cannot be converted directly to a number"Number(Bigint type) : returns a number without nNumber( "") : an empty string or space, returned0
Number(-10) : Returns -10
Number(+10) : returns10
Copy the code

In all other cases, the result is NaN whenever an invalid numeric character is present in the string

Implicit conversion (manual conversion)

  • Number() : by default, the browser converts to Number for calculation
  • Mathematical operations
  • Based on the == comparison
    • Some values need to be converted to numbers for comparison
  • IsNaN ([value]);

Thinking about?

How do I make obJ – 10 = 0?

let obj = {
  name: 'Guyal_'[Symbol.toPrimitive]() {
      return 10; }};console.log(obj-10);  / / 0
Copy the code
Analysis of the analysis

Since the object has symbol. toPrimitive and can call valueOf/toString, we can refactor these three methods to achieve the desired result. Let’s look at the implementation

The bottom layer calls the Symbol. ToPrimitive property of OBJ, obtains the original value, and then realizes the mathematical operation, the final result is 0

ParseInt/parseFloat?

parseInt

  • Syntax: parsetInt([val],[radix])
  • Parameters:
    • [val] : must be a string, if not, it is also converted to a string by default
    • [radix] : not set (or write zero) : normal processing is 10, default 16 if string starts with “0x”…
  • Return value: integer
  • To find the mechanism
    • Starting with the first character to the left of the string, it looks for a valid numeric character (stop looking for an invalid numeric character, regardless of whether there are any more numeric characters), converts any found valid numeric character to a number, and if none is found, the result is NaN
  • Processing mechanism
    • Find all contents consistent with [radix] in [val] first
    • I’m going to go from left to right until I see something that doesn’t match and I’m going to say, “I don’t care if there’s any more that matches the base.”
    • Hexadecimal conversion
      • Binary 0~1
      • Ternary “0~2”
      • Quad “0 to 3”
      • Octal “0 to 7”
      • Decimal “0 to 9”
      • The hexadecimal value is 09 A10F15″
    • And then find the content as [radix], conversion to decimal
    • [RADIX] range 2~36, except 0 (0->10/16), is not in this range, the result is NaN

parseFloat([val])

  • The second parameter is not supported
  • Recognize one more decimal point than parseInt, otherwise the same as parseInt

Object type to string type

application

  • String splicing

The difference between == and ===?

  • == Compare rules
    • If the two data types are inconsistent, they are converted to the same data type
      • Object == string “Object will be converted to string”
      • The rest of the cases are converted to numbers
        • Object == number
        • String == Boolean
        • String == number
        • Boolean == number
    • If the two sides have the same type, they start to compare; Object compares heap memory addresses
  • === compare rules
    • If the type is inconsistent, the conversion is not performed and false is returned

Insert a wave of questions

What is the output?

console.log([]==false);
console.log(! [] = =false);
Copy the code
  • console.log([]==false);
    • Object == booleans are converted to numbers (implicit conversion)
    • Object to number:
      • [].valueof is not a raw value, but a reference value, so call the [].toString() method, which results in “”(empty string),
      • Convert to numbers
        • “” Converts Number to type 0, false converts Number to type 0, so []==false ==> true
  • console.log(! []==false);
    • ! Value has a higher priority than ==
    • ! [] first converts to Boolean, [] converts to true, or false, so false==false ==>true
    • True for all strings except 0, NaN, null, undefined, and empty string whose Boolean value is false
    • Boolean([]); true
    • ! true = false

Implement the following code to print ‘OK’

var a = ?
if(a == 1 && a == 2 && a == 3) {
   console.lo('OK');
} 
Copy the code
  • Type 1: implicit data type conversion is processed
      1. Reconstructing Symbol. ToPrimitive/toString/valueOf
    var a = {
        i: 0
    }
    // Object == number, need to convert the object to number
    a[Symbol.toPrimitive] = function() {
        return ++this.i
    }
    if(a == 1 && a == 2 && a == 3) {
        console.log('OK');
    } 
    Copy the code
      1. Array toString method refactoring (Implementation tips)
    var a = [1.2.3];
    ToString (shift); toString (shift); toString (shift)
    a.toString = a.shift;
    if(a == 1 && a == 2 && a == 3) {
        console.log('OK');
    } 
    Copy the code
  • The second type: ES6 data hijacking
var i = 0;
Object.defineProperty(window.'a', {
    get() {
        return++i; }});if (a == 1 && a == 2 && a == 3) {
    console.log('OK');
}
Copy the code

Ali interview questions

let arr = [27.2.0.'0013'.'14px'.123];
arr = arr.map(parseInt);
console.log(arr);
Copy the code

Train of thought

  • Callback function: To pass one function as a value to another function (argument)
  • Map Usage
    • The number of items in the data, the number of iterations, each time to execute the callback function (item current iteration item index index), support the callback function return value, return what to replace the current item into what, the original array unchanged, to the new array return!!

Analysis: The results are: [27, NaN, 1, 1, 27]

parseInt(27.2.0) :27
parseInt(0.1) :NaN
parseInt('0013'.2) :'001'As a2Base conversion to10Into the system,1*2^0 -> 1
parseInt('14px'.3) :'1'As a3Base conversion to10Into the system,1*3^0 -> 1
parseInt(123.4) :'123'As a4Base conversion to10Into the system3*4^0 + 2*4^1 + 1*4^2 -> 3+8+16 -> 27
Copy the code