JavaScript随机正数或负数 [英] JavaScript Random Positive or Negative Number

查看:220
本文介绍了JavaScript随机正数或负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个随机的-1或1来乘以一个已经存在的数字.问题是我当前的随机函数生成-1、0或1.最有效的方法是什么?

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 this?

推荐答案

不使用您现有的功能-只需调用Math.random().如果< 0.5,然后是-1,否则为1:

Don't use your existing function - just call Math.random(). If < 0.5 then -1, else 1:

var plusOrMinus = Math.random() < 0.5 ? -1 : 1;

这篇关于JavaScript随机正数或负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆