JavaScript / TypeScript / 系统课时

Math 数学工具

Math 数学工具

JavaScript 的 Math 对象提供了一组无需实例化即可使用的数学工具。本篇通过实际计算场景学习随机数、绝对值、最大最小值、取整和幂运算方法,掌握日常开发中最常用的数学处理能力。

学习目标

  • 掌握 Math 常用方法的作用和调用方式
  • 能够使用随机数和取整方法完成常见业务逻辑
  • 理解不同取整方法在实际场景中的区别

使用 Math 基础方法

Math 是 JavaScript 内置对象,所有方法都通过静态方式调用,例如 Math.max() 和 Math.floor()。

js
const values = [8, 3, 12, 5];

console.log(Math.max(...values));
console.log(Math.min(...values));
console.log(Math.abs(-15));

预期输出

text
12
3
15

常用方法包括:

方法 作用
Math.max() 返回最大值
Math.min() 返回最小值
Math.abs() 返回绝对值
Math.pow() 计算幂
Math.sqrt() 计算平方根

使用取整方法处理小数

Math 提供了多个取整方法,它们的区别在于处理小数部分的规则不同。

js
const number = 4.8;

console.log(Math.floor(number));
console.log(Math.ceil(number));
console.log(Math.round(number));
console.log(Math.trunc(number));

预期输出

text
4
5
5
4
方法 处理规则
Math.floor() 向下取整
Math.ceil() 向上取整
Math.round() 四舍五入
Math.trunc() 直接去掉小数部分

处理负数时需要特别注意,例如 Math.floor(-1.2) 的结果是 -2,因为它始终向负无穷取整。

生成随机数

Math.random() 会返回大于等于 0 且小于 1 的随机小数,常用于验证码、抽样和游戏逻辑。

js
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(randomInt(1, 10));

预期输出

text
7

输出中的数字每次运行可能不同,但范围始终是 1 到 10。

使用幂运算和平方根

Math 可以处理基础指数计算。

js
const result = Math.pow(2, 3);
const square = Math.sqrt(25);

console.log(result);
console.log(square);

预期输出

text
8
5

现代 JavaScript 中也可以使用指数运算符完成幂计算:

js
const value = 2 ** 3;

console.log(value);

预期输出

text
8

根据场景选择 Math 方法

数据展示通常使用 Math.round() 配合格式化处理;分页、数组下标等场景更常使用 Math.floor();需要保证范围覆盖时可以使用 Math.ceil()。

随机数、取整和范围计算是前端交互中非常常见的组合。掌握这些方法后,可以减少手写计算逻辑带来的边界错误。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

Math 数学工具

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通