Number.sign() in javascript

前端 未结 15 2295
日久生厌
日久生厌 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:47

    Very similar to Martijn's answer is

    function sgn(x) {
        isNaN(x) ? NaN : (x === 0 ? x : (x < 0 ? -1 : 1));
    }
    

    I find it more readable. Also (or, depending on your point of view, however), it also groks things that can be interpreted as a number; e.g., it returns -1 when presented with '-5'.

提交回复
热议问题