JavaScript Random Positive or Negative Number

后端 未结 6 1860
孤独总比滥情好
孤独总比滥情好 2021-01-30 06:32

I need to create a random -1 or 1 to multiply an already existing number by. Issue is my current random function generates a -1, 0, or 1. What is the most efficient way of doing

6条回答
  •  滥情空心
    2021-01-30 07:14

    I've always been a fan of

    Math.round(Math.random()) * 2 - 1
    

    as it just sort of makes sense.

    • Math.round(Math.random()) will give you 0 or 1

    • Multiplying the result by 2 will give you 0 or 2

    • And then subtracting 1 gives you -1 or 1.

    Intuitive!

提交回复
热议问题