JavaScript中Math對(duì)象和隨機(jī)數(shù)的實(shí)際應(yīng)用及注意事項(xiàng)
一、常用數(shù)學(xué)方法
1. 數(shù)值處理
方法 | 說明 | 示例 |
---|---|---|
Math.abs(x) | 絕對(duì)值 | 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) | 返回符號(hào)(-1, 0, 1) | Math.sign(-5) → -1 |
2. 極值與運(yùn)算
方法 | 說明 | 示例 |
---|---|---|
Math.max(a, b, ...) | 返回最大值 | Math.max(1, 3, 2) → 3 |
Math.min(a, b, ...) | 返回最小值 | Math.min(1, -3, 2) → -3 |
Math.pow(base, exp) | 冪運(yùn)算(等效 ** ) | 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. 對(duì)數(shù)與指數(shù)
方法 | 說明 | 示例 |
---|---|---|
Math.log(x) | 自然對(duì)數(shù)(底為 e) | Math.log(Math.E) → 1 |
Math.log10(x) | 以 10 為底的對(duì)數(shù) | Math.log10(100) → 2 |
Math.log2(x) | 以 2 為底的對(duì)數(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 |
二、隨機(jī)數(shù)生成 Math.random()
Math.random()
返回 [0, 1) 區(qū)間內(nèi)的浮點(diǎn)數(shù)(包含 0,不包含 1)。
1. 基礎(chǔ)范圍控制
生成 [0, max) 的浮點(diǎn)數(shù):
const randomFloat = Math.random() * max;
生成 [min, max) 的浮點(diǎn)數(shù):
const randomFloat = Math.random() * (max - min) + min;
2. 整數(shù)隨機(jī)數(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; }
三、實(shí)際應(yīng)用場(chǎng)景
1. 隨機(jī)顏色生成
// 生成十六進(jìn)制顏色 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ù)組隨機(jī)排序
// 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; } // 簡(jiǎn)易版(不保證均勻性) const randomSort = array => array.sort(() => Math.random() - 0.5);
3. 概率控制
// 30% 概率觸發(fā)事件 if (Math.random() < 0.3) { console.log("觸發(fā)成功!"); } // 加權(quán)隨機(jī)(如 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; } }
四、注意事項(xiàng)
不要用于加密場(chǎng)景
Math.random()
的隨機(jī)性不安全,如需加密請(qǐng)使用crypto.getRandomValues()
:const array = new Uint32Array(1); window.crypto.getRandomValues(array); // 生成安全隨機(jī)數(shù)
避免浮點(diǎn)誤差浮點(diǎn)數(shù)運(yùn)算可能存在精度問題,處理金額等敏感數(shù)據(jù)時(shí)建議轉(zhuǎn)成整數(shù)計(jì)算。
范圍閉合問題確保公式正確閉合區(qū)間(如
[min, max]
vs[min, max)
)。種子隨機(jī)數(shù)JavaScript 原生不支持種子隨機(jī)數(shù),需自行實(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()
總結(jié)
到此這篇關(guān)于JavaScript中Math對(duì)象和隨機(jī)數(shù)的實(shí)際應(yīng)用及注意事項(xiàng)的文章就介紹到這了,更多相關(guān)JS中Math對(duì)象和隨機(jī)數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
去除JavaScript對(duì)象中空值和空對(duì)象的四種方式
開發(fā)時(shí)遇到一個(gè)問題,需要將對(duì)象中的空值和空對(duì)象去除,所以這篇文章主要給大家介紹了關(guān)于去除JavaScript對(duì)象中空值和空對(duì)象的四種方式,需要的朋友可以參考下2023-09-09JavaScript使用forEach()與jQuery使用each遍歷數(shù)組時(shí)return false 的區(qū)別
這篇文章主要介紹了JavaScript使用forEach()與jQuery使用each遍歷數(shù)組時(shí)return false 的區(qū)別,非常不錯(cuò),需要的朋友可以參考下2016-08-08淺談高大上的微信小程序中渲染html內(nèi)容—技術(shù)分享
大部分Web應(yīng)用的富文本內(nèi)容都是以HTML字符串的形式存儲(chǔ)的,那么在微信小程序中,應(yīng)當(dāng)如何渲染這部分內(nèi)容呢?感興趣的小伙伴們可以參考一下2018-10-10原生JavaScript輪播圖實(shí)現(xiàn)方法
這篇文章主要為大家詳細(xì)介紹了原生JavaScript輪播圖實(shí)現(xiàn)方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08BootstrapTable+KnockoutJS相結(jié)合實(shí)現(xiàn)增刪改查解決方案(三)兩個(gè)Viewmodel搞定增刪改查
這篇文章主要介紹了BootstrapTable+KnockoutJS相結(jié)合實(shí)現(xiàn)增刪改查解決方案(三)兩個(gè)Viewmodel搞定增刪改查 的相關(guān)資料,需要的朋友可以參考下2016-08-08Electron 打包問題:electron-builder 下載各種依賴出錯(cuò)(推薦)
這篇文章主要介紹了Electron 打包問題:electron-builder 下載各種依賴出錯(cuò),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07