文章詳情頁
javascript - JS如何取對稱范圍的隨機數?
瀏覽:185日期:2023-03-27 11:09:57
問題描述
比如我想用 Math.random() 取 -20~-10 和 10~20 這兩個范圍的隨機數,有什么最有精簡的解決方案嗎?比如不用 if 語句能不能做到?謝謝大家解惑。
問題解答
回答1:(Math.floor(Math.random() * (20 - 10 + 1)) + 10) * (Math.random() < 0.5 ? -1 : 1)回答2:
function getRandom(min,max){ return Math.random()*(max-min)+min;}回答3:
Math.random() * (max - min) + min;
詳見
修改:
(Math.random() * (max - min) + min)*(Math.random()<0.5?1:-1);回答4:
function rand(min, max) { if ( min >= max ) {return; } return Math.floor(min + (max - min+1) * Math.random());}
這是取一個范圍內整數的
標簽:
JavaScript
上一條:javascript - 靜態頁面html 引頭尾公共文件?下一條:javascript - JS使用ele.style.backgoundImage = ’’ =’none’取消背景圖片都無效
相關文章:
1. python文檔怎么查看?2. java - 在用戶不登錄的情況下,用戶如何添加保存到購物車?3. java - spring boot 如何打包成asp.net core 那種獨立應用?4. javascript - 關于apply()與call()的問題5. android - SwipeRefreshLayout5.0以下不兼容6. html - eclipse 標簽錯誤7. javascript - webpack 分割加載代碼后,react 界面不更新8. javascript - nginx反向代理靜態資源403錯誤?9. datetime - Python如何獲取當前時間10. 安全性測試 - nodejs中如何防mySQL注入
排行榜
