Coerce to number

后端 未结 4 953
半阙折子戏
半阙折子戏 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: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

提交回复
热议问题