欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript中Math對(duì)象和隨機(jī)數(shù)的實(shí)際應(yīng)用及注意事項(xiàng)

 更新時(shí)間:2025年05月07日 10:00:33   作者:旺代  
這篇文章主要介紹了JavaScript中Math對(duì)象和隨機(jī)數(shù)的實(shí)際應(yīng)用及注意事項(xiàng),包括數(shù)值處理、極值與運(yùn)算、三角函數(shù)、對(duì)數(shù)與指數(shù)、常量、隨機(jī)數(shù)生成及其應(yīng)用場(chǎ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.PI3.141592653589793
Math.E2.718281828459045
Math.LN20.6931471805599453
Math.SQRT21.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)文章

最新評(píng)論