javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JS中Math对象和随机数

JavaScript中Math对象和随机数的实际应用及注意事项

作者:旺代

这篇文章主要介绍了JavaScript中Math对象和随机数的实际应用及注意事项,包括数值处理、极值与运算、三角函数、对数与指数、常量、随机数生成及其应用场景和注意事项,需要的朋友可以参考下

一、常用数学方法

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. 基础范围控制

2. 整数随机数

三、实际应用场景

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:

<!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}, ${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()

总结 

到此这篇关于JavaScript中Math对象和随机数的实际应用及注意事项的文章就介绍到这了,更多相关JS中Math对象和随机数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文