Coerce to number

后端 未结 4 930
半阙折子戏
半阙折子戏 2020-12-15 17:35

I have often seen the trick

after = +after;

to coerce the variable after to a number. Reading through the Node.JS source I fou

相关标签:
4条回答
  • 2020-12-15 18:13

    After a quick google to make sure my suspicions were true, I came to this conclusion. Using the + operator to convert to a number is faster, because no mathematical operations occur after type-casting, whereas using the *= approach means that after after is converted, it will be multiplied by 1.

    0 讨论(0)
  • 2020-12-15 18:22

    Yes. Both Unary Operator + and Multiplicative Operators such as * (called from Compound Assignment op=) invoke the internal ToNumber algorithm.

    You can even use a 3rd option by statically calling the Number constructor:

    after = Number(after);
    
    0 讨论(0)
  • 2020-12-15 18:24

    Yes, however note that it is only the unary + operator that does this. I.e. 10 + "10" will give you "1010".

    A perhaps less error prone option is to use what asm.js does:

    10 + ("10"|0)
    

    Although on the down-side it does require the brackets. It should be the fastest option in any case (probably equal to unary +).

    0 讨论(0)
  • 2020-12-15 18:32

    Note: In some instances after = after-0 invokes different behaviour than after = after+0. I've noticed it with dates.

    This is tested in Chrome v39 only:

    var date = new Date(2000,0,1);
    date += date; //"Sat Jan 01 2000 00:00:00 GMT+0000 (GMT Standard Time)Sat Jan 01 2000 00:00:00 GMT+0000 (GMT Standard Time)"
    var date2 = new Date(2000,0,1);
    date2 + 0; //"Sat Jan 01 2000 00:00:00 GMT+0000 (GMT Standard Time)0"
    date2 - 0; //946684800000
    date2 * 1; //946684800000
    

    I don't know what is defined in the JS spec, but with dates, because both the date and the number can be cast to a string, and the + operator works on a string, then Chrome goes with a string concatenation. Because the - operator has no string equivalent, it falls back to number comparison.

    I've found this useful when coercing dates into numbers for comparisons

    0 讨论(0)
提交回复
热议问题