跳到主要内容

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
Date.now();        // 当前时间戳(毫秒)
d.getTime(); // 转为时间戳
new Date(0); // 1970 年起始时间
d.toISOString(); // 格式化为 ISO 字符串
d.toLocaleString(); // 本地时间字符串

String 对象

字符串是不可变的,常用方法都会返回新字符串


字符访问

js
const str = "JavaScript";
str.length; // 10
str[0]; // "J"
str.charAt(1); // "a"

搜索与匹配

js
str.indexOf("a");     // 1
str.lastIndexOf("a"); // 3
str.includes("Script"); // true
str.startsWith("Java"); // true
str.endsWith("pt"); // true

截取与分割

js
str.slice(0, 4);    // "Java"
str.substring(4, 10); // "Script"
str.split("a"); // ["J", "v", "Script"]

大小写转换

js
str.toUpperCase(); // "JAVASCRIPT"
str.toLowerCase(); // "javascript"

替换与拼接

js
str.replace("Java", "Type"); // "TypeScript"
"Hello".concat(" ", "World"); // "Hello World"

去除空格

js
"  JS  ".trim();   // "JS"
" JS ".trimStart(); // 去前空格
" JS ".trimEnd(); // 去后空格

模板字符串(ES 6)

js
const name = "Alice";
const msg = `Hello, ${name}!`;
console.log(msg); // "Hello, Alice!"