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;
}
}
四、注意事项
-
不要用于加密场景
Math.random()
的随机性不安全,如需加密请使用crypto.getRandomValues()
:const array = new Uint32Array(1); window.crypto.getRandomValues(array); // 生成安全随机数
-
避免浮点误差
浮点数运算可能存在精度问题,处理金额等敏感数据时建议转成整数计算。 -
范围闭合问题
确保公式正确闭合区间(如[min, max]
vs[min, max)
)。 -
种子随机数
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()