JavaScript中Math對象和隨機數(shù)的實際應用及注意事項
一、常用數(shù)學方法
1. 數(shù)值處理
方法 | 說明 | 示例 |
---|---|---|
Math.abs(x) | 絕對值 | Math.abs(-5) → 5 |
Math.round(x) | 四舍五入 | Math.round(4.7) → 5 |
Math.floor(x) | 向下取整(地板值) | Math.floor(4.9) → 4 |
Math.ceil(x) | 向上取整(天花板值) | Math.ceil(4.1) → 5 |
Math.trunc(x) | 去除小數(shù)部分 | Math.trunc(4.9) → 4 |
Math.sign(x) | 返回符號(-1, 0, 1) | Math.sign(-5) → -1 |
2. 極值與運算
方法 | 說明 | 示例 |
---|---|---|
Math.max(a, b, ...) | 返回最大值 | Math.max(1, 3, 2) → 3 |
Math.min(a, b, ...) | 返回最小值 | Math.min(1, -3, 2) → -3 |
Math.pow(base, exp) | 冪運算(等效 ** ) | Math.pow(2, 3) → 8 |
Math.sqrt(x) | 平方根 | Math.sqrt(16) → 4 |
Math.cbrt(x) | 立方根 | Math.cbrt(27) → 3 |
Math.hypot(a, b, ...) | 平方和的平方根 | Math.hypot(3, 4) → 5 |
3. 三角函數(shù)(參數(shù)為弧度)
方法 | 說明 | 示例 |
---|---|---|
Math.sin(radians) | 正弦值 | Math.sin(Math.PI/2) → 1 |
Math.cos(radians) | 余弦值 | Math.cos(0) → 1 |
Math.tan(radians) | 正切值 | Math.tan(Math.PI/4) ≈ 1 |
Math.asin(x) | 反正弦(弧度) | Math.asin(1) → π/2 |
Math.atan2(y, x) | 四象限反正切 | Math.atan2(1, 1) → π/4 |
4. 對數(shù)與指數(shù)
方法 | 說明 | 示例 |
---|---|---|
Math.log(x) | 自然對數(shù)(底為 e) | Math.log(Math.E) → 1 |
Math.log10(x) | 以 10 為底的對數(shù) | Math.log10(100) → 2 |
Math.log2(x) | 以 2 為底的對數(shù) | Math.log2(8) → 3 |
Math.exp(x) | e 的 x 次冪 | Math.exp(1) → Math.E ≈ 2.718 |
5. 常量
常量 | 值(約) |
---|---|
Math.PI | 3.141592653589793 |
Math.E | 2.718281828459045 |
Math.LN2 | 0.6931471805599453 |
Math.SQRT2 | 1.4142135623730951 |
二、隨機數(shù)生成 Math.random()
Math.random()
返回 [0, 1) 區(qū)間內的浮點數(shù)(包含 0,不包含 1)。
1. 基礎范圍控制
生成 [0, max) 的浮點數(shù):
const randomFloat = Math.random() * max;
生成 [min, max) 的浮點數(shù):
const randomFloat = Math.random() * (max - min) + min;
2. 整數(shù)隨機數(shù)
生成 [0, max] 的整數(shù)(包含 max):
const randomInt = Math.floor(Math.random() * (max + 1));
生成 [min, max] 的整數(shù)(經(jīng)典公式):
function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
三、實際應用場景
1. 隨機顏色生成
// 生成十六進制顏色 function getRandomHexColor() { return `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')}`; } // 生成 RGB 顏色 function getRandomRGB() { const r = Math.floor(Math.random() * 256); const g = Math.floor(Math.random() * 256); const b = Math.floor(Math.random() * 256); return `rgb(${r}, ${g}, $)`; }
2. 數(shù)組隨機排序
// Fisher-Yates 洗牌算法(推薦) function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } return array; } // 簡易版(不保證均勻性) const randomSort = array => array.sort(() => Math.random() - 0.5);
3. 概率控制
// 30% 概率觸發(fā)事件 if (Math.random() < 0.3) { console.log("觸發(fā)成功!"); } // 加權隨機(如 60% A,30% B,10% C) const weights = { A: 0.6, B: 0.3, C: 0.1 }; function weightedRandom(weights) { let sum = 0; const rand = Math.random(); for (const [key, weight] of Object.entries(weights)) { sum += weight; if (rand < sum) return key; } }
四、注意事項
不要用于加密場景
Math.random()
的隨機性不安全,如需加密請使用crypto.getRandomValues()
:const array = new Uint32Array(1); window.crypto.getRandomValues(array); // 生成安全隨機數(shù)
避免浮點誤差浮點數(shù)運算可能存在精度問題,處理金額等敏感數(shù)據(jù)時建議轉成整數(shù)計算。
范圍閉合問題確保公式正確閉合區(qū)間(如
[min, max]
vs[min, max)
)。種子隨機數(shù)JavaScript 原生不支持種子隨機數(shù),需自行實現(xiàn)算法(如 Xorshift)。
示例1:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>test</title> <link rel="stylesheet" href="./base.css" rel="external nofollow" > <style> table { border-collapse: collapse; border-spacing: 0; margin: 50px auto; } td, th { border: 1px solid #ddd; padding: 10px; text-align: center; } th { background-color: #c1c1c1; } </style> </head> <body> <table> <tr> <th>name</th> <th>age</th> <th>gender</th> <th>hometown</th> </tr> <script> let students = [ { name: '小明1', age: '18', gender: '男', hometown: '河北省' }, { name: '小明2', age: '18', gender: '男', hometown: '河北省' }, { name: '小明3', age: '18', gender: '男', hometown: '河北省' }, { name: '小明4', age: '18', gender: '男', hometown: '河北省' }, ] for (let i = 0; i < students.length; i++) { document.write(` <tr> <td>${students[i].name}</td> <td>${students[i].age}</td> <td>${students[i].gender}</td> <td>${students[i].hometown}</td> </tr> `) } </script> </table> </body> </html>
示例2:
function getColor() { let r = Math.floor(Math.random() * 256) let g = Math.floor(Math.random() * 256) let b = Math.floor(Math.random() * 256) let color = `rgb(${r}, ${g}, $)` return color; } let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'] function getColor() { let str = '#' for (let i = 0; i < 6; i++) { str += data[Math.floor(Math.random() * data.length)] } return str } const div = document.querySelector('div') div.style.backgroundColor = getColor()
總結
到此這篇關于JavaScript中Math對象和隨機數(shù)的實際應用及注意事項的文章就介紹到這了,更多相關JS中Math對象和隨機數(shù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JavaScript使用forEach()與jQuery使用each遍歷數(shù)組時return false 的區(qū)別
這篇文章主要介紹了JavaScript使用forEach()與jQuery使用each遍歷數(shù)組時return false 的區(qū)別,非常不錯,需要的朋友可以參考下2016-08-08BootstrapTable+KnockoutJS相結合實現(xiàn)增刪改查解決方案(三)兩個Viewmodel搞定增刪改查
這篇文章主要介紹了BootstrapTable+KnockoutJS相結合實現(xiàn)增刪改查解決方案(三)兩個Viewmodel搞定增刪改查 的相關資料,需要的朋友可以參考下2016-08-08Electron 打包問題:electron-builder 下載各種依賴出錯(推薦)
這篇文章主要介紹了Electron 打包問題:electron-builder 下載各種依賴出錯,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07