JavaScript里的Math对象及随机数探究

8小时前发布 gsjqwyl
2 0 0

文章标题:

JavaScript中Math对象与随机数的探索

文章内容:

目录

一、常见数学方法

  1. 数值的处理
  2. 极值与运算
  3. 三角函数(参数为弧度)
  4. 对数与指数相关
  5. 常量

二、随机数生成Math.random()

  1. 基础范围的把控
  2. 整数随机数的获取

三、实际应用情形

  1. 随机颜色的生成
  2. 数组的随机排序
  3. 概率的把控

四、注意事项


一、常见数学方法

1. 数值的处理

方法 说明 示例
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) 去除小数部分 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. 三角函数(参数为弧度)

方法 说明 示例
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. 对数与指数

方法 说明 示例
Math.log(x) 自然对数(底为 e) Math.log(Math.E) → 1
Math.log10(x) 以 10 为底的对数 Math.log10(100) → 2
Math.log2(x) 以 2 为底的对数 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

二、随机数生成Math.random()

Math.random()会返回一个处于[0, 1)区间内的浮点数,包含0但不包含1。

1. 基础范围控制

  • 生成 [0, max) 的浮点数

    const randomFloat = Math.random() * max;
    
  • 生成 [min, max) 的浮点数

    const randomFloat = Math.random() * (max - min) + min;
    

2. 整数随机数

  • 生成 [0, max] 的整数(包含 max)

    const randomInt = Math.floor(Math.random() * (max + 1));
    
  • 生成 [min, max] 的整数(经典公式)

    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}, ${b})`;
}

2. 数组随机排序

// 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% 概率触发事件
if (Math.random() < 0.3) {
  console.log("触发成功!");
}

// 加权随机(如 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;
  }
}

四、注意事项

  1. 勿用于加密场景
    Math.random()的随机性不安全 ,若需加密可使用 crypto.getRandomValues()

     const array = new Uint32Array(1);
     window.crypto.getRandomValues(array); // 生成安全随机数
    
  2. 规避浮点误差
    浮点数运算可能存在精度问题,处理金额等敏感数据时建议转为整数计算。

  3. 范围闭合问题
    需确保公式正确闭合区间(如 [min, max][min, max) 的区别)。

  4. 种子随机数
    JavaScript 原生不支持种子随机数,可自行实现算法(如
    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">
    <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}, ${b})`
    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()
© 版权声明

相关文章

暂无评论

暂无评论...