Number.sign() in javascript

前端 未结 15 2276
日久生厌
日久生厌 2020-11-30 21:03

Wonder if there are any nontrivial ways of finding number\'s sign (signum function)?
May be shorter / faster / more elegant solutions than the obvious one



        
15条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 21:28

    For people who are interested what is going on with latest browsers, in ES6 version there is a native Math.sign method. You can check the support here.

    Basically it returns -1, 1, 0 or NaN

    Math.sign(3);     //  1
    Math.sign(-3);    // -1
    Math.sign('-3');  // -1
    Math.sign(0);     //  0
    Math.sign(-0);    // -0
    Math.sign(NaN);   // NaN
    Math.sign('foo'); // NaN
    Math.sign();      // NaN
    

提交回复
热议问题