JS Math、Date、String
Math 对象
Math 是一个静态对象,不需要实例化,直接通过 Math. 调用。
常用属性
js
Math.PI // 圆周率 π
Math.E // 自然常数 e
Math.SQRT2 // √2
常用方法
js
Math.abs(-5); // 5 绝对值
Math.max(1, 9); // 9 最大值
Math.min(1, 9); // 1 最小值
Math.pow(2, 3); // 8 幂运算
Math.sqrt(16); // 4 平方根
Math.ceil(2.3); // 3 向上取整
Math.floor(2.9); // 2 向下取整
Math.round(2.5); // 3 四舍五入
Math.random(); // [0,1) 随机数
随机数常用写法
js
// 0~9 的随机整数
Math.floor(Math.random() * 10);
// 1~100 的随机整 数
Math.floor(Math.random() * 100) + 1;
Date 对象
Date 用于表示日期和时间。
创建时间对象
js
const now = new Date(); // 当前时间
const d1 = new Date("2025-10-04"); // 指定日期
const d2 = new Date(2025, 9, 4); // 注意:月份从 0 开始(9 表示 10 月)
获取时间信息
js
const d = new Date();
d.getFullYear(); // 年份
d.getMonth(); // 月份(0~11)
d.getDate(); // 日期(1~31)
d.getDay(); // 星期(0=周日)
d.getHours(); // 小时
d.getMinutes(); // 分钟
d.getSeconds(); // 秒
设置时间信息
js
const d = new Date();
d.setFullYear(2030);
d.setMonth(11);
d.setDate(25);
时间戳与格式化
js