Number.sign() in javascript

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

    I just was about to ask the same question, but came to a solution before i was finished writing, saw this Question already existed, but didn't saw this solution.

    (n >> 31) + (n > 0)

    it seems to be faster by adding a ternary though (n >> 31) + (n>0?1:0)

提交回复
热议问题