当前位置: 首页 > news >正文

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.PI3.141592653589793
Math.E2.718281828459045
Math.LN20.6931471805599453
Math.SQRT21.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] vs [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()

http://www.dtcms.com/a/98906.html

相关文章:

  • [ 春秋云境 ] Initial 仿真场景
  • Linux系统中应用端控制串口的基本方法
  • GEO(生成引擎优化)实施策略全解析:从用户意图到效果追踪
  • CANoe入门——CANoe的诊断模块,调用CAPL进行uds诊断
  • 鸿蒙项目源码-外卖点餐-原创!原创!原创!
  • 【算法】二分查找总结篇
  • Java网页消息推送解决方案
  • 累积分布策略思路
  • ModuleNotFoundError: No module named ‘ml_logger.logbook‘
  • 组件组合和Context API在React中的应用
  • Go 语言规范学习(4)
  • 从系统架构、API对接核心技术、业务场景设计及实战案例四个维度,深度解析1688代采系统
  • 征程 6E mipi tx 系列之方案介绍
  • 知能行每日刷题
  • 【2.项目管理】2.7 进度控制习题-2
  • 蓝桥杯省模拟赛 字符串拼接
  • 基于Web的交互式智能成绩管理系统设计
  • 【书籍】DeepSeek谈《软件开发的201个原则》
  • 从Manus到OpenManus:AI智能体技术如何重塑未来生活场景?
  • vector的模拟实现01
  • C++运算符重载、类的转换构造函数和类型转换函数的基础练习
  • 【SPP】蓝牙串口协议应用层深度解析:从连接建立到实战开发
  • 解决Dubbo3调用Springcloud接口报No provider available from registry RegistryDirectory
  • 【java基础】Java 泛型
  • IPv6 Over IPv4 自动 6to4 隧道
  • Altium Designer——同时更改多个元素的属性(名称、网络标签、字符串标识)
  • OpenBMC:BmcWeb 生效路由5 优化trie
  • Unity高渲染管线
  • 经济均衡问题建模与求解:单一市场供需平衡分析
  • 蓝桥杯单片机刷题——E2PROM记录开机次数