Skip to content

JavaScript 内置对象:Math、Date、RegExp 与 JSON

语言内置的这四个对象是业务代码的日用品:算价格用 Math、排期显示用 Date、校验输入用 RegExp、前后端交互用 JSON。这篇按"用法 → 坑 → 实战"的结构逐个过,主线是现代浏览器(ES2022)。

一、Math 对象

1.1 常量与方法

js
Math.PI;            // 3.141592653589793
Math.E;             // 2.718281828459045
Math.SQRT2;         // √2

Math.abs(-5);       // 5 绝对值
Math.sign(-3);      // -1(正数 1、零 0、NaN 得 NaN)
Math.ceil(4.1);     // 5 向上取整
Math.floor(4.9);    // 4 向下取整
Math.trunc(4.9);    // 4 截断取整(-4.9 得 -4,和 floor 区分)
Math.round(4.5);    // 5(.5 向上,但 -4.5 得 -4,不对称)
Math.max(1, 2, 3);  // 3,空参得 -Infinity
Math.min(1, 2, 3);  // 1
Math.pow(2, 10);    // 1024(等价 2 ** 10)
Math.sqrt(16);      // 4
Math.cbrt(27);      // 3 立方根
Math.hypot(3, 4);   // 5 勾股定理 √(x²+y²)

Math.round 的 .5 行为和 trunc 的区别在负数上最容易记混,写"抹掉小数"一律 Math.trunc,写"四舍五入"用 Math.round 但要测负数场景。

1.2 随机数

js
Math.random();                       // [0, 1) 伪随机
Math.floor(Math.random() * 100);     // 0-99 整数
Math.floor(Math.random() * 100) + 1; // 1-100 整数

// 区间整数通用函数
function randInt(min, max) {        // 含 min 含 max
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
randInt(1, 6);                       // 骰子

// 数组随机取一
const pick = arr => arr[randInt(0, arr.length - 1)];

// 洗牌(Fisher-Yates,比 sort(() => Math.random() - 0.5) 均匀)
function shuffle(arr) {
  const a = [...arr];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

两个必须知道的点:

  1. Math.random() 是伪随机且不可设种子,要可复现的随机序列得自己实现 LCG 或用 seedrandom 类库
  2. 安全敏感场景(token、密码、验证码)不能用它,要用 crypto.getRandomValues:
js
// 安全随机整数
function secureRandInt(max) {
  const arr = new Uint32Array(1);
  crypto.getRandomValues(arr);
  return arr[0] % max;   // 严格做法要拒绝采样消偏,演示级够用
}
// 安全随机 token
crypto.randomUUID();     // 'a1b2c3d4-...',Chrome 92+/Safari 15.4+

sort(() => Math.random() - 0.5) 是经典错洗牌:比较函数不一致,分布不均且依赖引擎实现,别用。

二、Date 对象

2.1 创建与读取

js
const now = new Date();                    // 当前时间
new Date(2024, 9, 22);                     // 本地时间 2024-10-22 00:00(月份从 0 起!)
new Date('2024-10-22T08:00:00+08:00');     // ISO 字符串(推荐,无歧义)
new Date('2024-10-22');                    // 按 UTC 解析!和上式差 8 小时
new Date(1729564800000);                   // 毫秒时间戳

now.getFullYear();       // 年
now.getMonth();          // 月 0-11(+1 才是人类月份)
now.getDate();           // 日 1-31
now.getDay();            // 星期 0(周日)-6
now.getHours();          // 时(本地时区)
now.getUTCHours();       // 时(UTC)——本地和 UTC 方法成对存在

now.getTime();           // 毫秒时间戳
Date.now();              // 同上,不用建对象,计时首选

月份从 0 开始:new Date(2024, 10, 1) 是 11 月 1 日,写 10 想表示 10 月会静默错一个月。日期字符串格式:YYYY-MM-DD(无时间部分)按 UTC 解析,带 T 和时区的按 ISO 精确解析——new Date('2024-10-22') 在东八区得到的是 UTC 0 点即早上 8 点,日期显示可能差一天。

2.2 设置与运算

js
const d = new Date();
d.setFullYear(2025);
d.setMonth(0);            // 改成本年 1 月
d.setDate(d.getDate() + 7);   // 7 天后(自动跨月跨年)

const dayMs = 24 * 60 * 60 * 1000;
const tomorrow = new Date(Date.now() + dayMs);   // 时间戳运算最可靠

const diffDays = (d2 - d1) / dayMs;   // 两个 Date 相减得毫秒差

2.3 格式化

js
// toLocaleString 家族:本地化首选,比手拼字符串靠谱
d.toLocaleString('zh-CN');                    // '2024/10/22 08:00:00'
d.toLocaleDateString('zh-CN');                // '2024/10/22'
d.toLocaleTimeString('zh-CN', { hour12: false });  // '08:00:00'

// Intl.DateTimeFormat:可复用,时区可控
const fmt = new Intl.DateTimeFormat('zh-CN', {
  year: 'numeric', month: '2-digit', day: '2-digit',
  hour: '2-digit', minute: '2-digit', hour12: false,
  timeZone: 'Asia/Shanghai',
});
fmt.format(d);                                // '2024/10/22 08:00'

d.toISOString();        // '2024-10-22T00:00:00.000Z'——给后端传这个,无时区歧义
d.toJSON();             // 同 toISOString,JSON.stringify 默认调用它

和前端交互的约定:存和传一律用 UTC ISO 字符串或时间戳,展示才转本地时区。把 toLocaleString 的结果直接提交给后端,换台机器时区就变了,是最常见的"BUG 只在同事机器上复现"来源。

2.4 时区坑

js
const d = new Date('2024-10-22T16:00:00+08:00');
d.getHours();                  // 本地时区的小时——用户在哪个时区看哪个结果
d.getUTCHours();               // 8

// 服务端传 UTC 时间戳,前端展示:
new Date(1729593600000).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });

用户系统时区不一定是业务时区(海外用户看国内活动时间),需要固定时区就用 timeZone 选项,别用 getHours 裸取。

2.5 性能计时

js
const t0 = performance.now();
heavyTask();
console.log(`耗时 ${performance.now() - t0}ms`);   // 毫秒,微秒级精度

Date.now() 毫秒精度且受系统时间影响(用户改系统时间能让"倒计时"瞬间错乱),倒计时、防抖节流、帧率统计用 performance.now()。

三、RegExp 对象

3.1 创建与标志位

js
const r1 = /ab+c/gi;           // 字面量:常用
const r2 = new RegExp('ab+c', 'gi');   // 构造函数:模式要动态拼时用
标志含义
g全局(多次匹配,lastIndex 会被记住)
i忽略大小写
m多行(^/$ 匹配每行首尾)
sdotAll(. 匹配换行)
uUnicode 模式(正确处理码点)
y粘性(从 lastIndex 起匹配)

正则字面量每次求值返回同一个对象(ES5+ 规范),而 new RegExp 每次新建——循环里用字面量时 lastIndex 状态在迭代间残留的坑主要和 g 标志有关:

js
const re = /\d/g;
re.test('a1');   // true
re.test('a1');   // false!lastIndex 停在 1,下次从后面找
re.lastIndex = 0; // 重置后才能复用

模块级共享的正则如果带 g,要么每次用前重置 lastIndex,要么用 String.prototype.match 系列(它们内部会处理)。

3.2 匹配方法

js
const text = '订单号:A2024,金额:99.5 元';
const numRe = /\d+/;

numRe.test(text);             // true——只判断有没有

// exec:返回匹配详情数组(带 index、groups),配 g 循环提取全部
let m;
while ((m = numRe.exec(text)) !== null) {
  console.log(m[0], m.index);   // '2024' 4 ; '99' ...; '5' ...
}

// match:字符串调正则
text.match(/\d+/g);           // ['2024', '99', '5']——g 标志返回全部匹配值
text.match(/\d+/);            // ['2024', index: 4, ...]——无 g 返回第一个详情
text.matchAll(/\d+/g);        // 迭代器,每项含 groups,比 while+exec 干净

// replace:替换
'2024-10-22'.replace(/-/g, '/');          // '2024/10/22'
'a1b2'.replace(/(\w)(\d)/g, '$2$1');      // '1a2b'($1 反向引用)
'a1b2'.replace(/(?<letter>\w)(?<digit>\d)/g, '$<digit>$<letter>');  // 命名组

// split:按正则切
'a1b22c'.split(/\d+/);        // ['a', 'b', 'c']

replace 第二参是函数时能拿到匹配、分组、位置,做模板替换、转义都用它:

js
// 模板渲染:把 {name} 替换成数据
function render(tpl, data) {
  return tpl.replace(/\{(\w+)\}/g, (_, key) => data[key] ?? '');
}
render('你好,{name}!', { name: '世界' });   // '你好,世界!'

// HTML 转义
function escapeHtml(s) {
  const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
  return s.replace(/[&<>"']/g, c => map[c]);
}
escapeHtml('<script>');   // '&lt;script&gt;'

3.3 语法速查

js
/abc/          // 字面量序列
/[abc]/        // 字符类:a 或 b 或 c
/[^abc]/       // 排除
/[a-z0-9]/     // 区间
/\d/ \D/       // 数字 [0-9] / 非数字
/\w/ \W/       // 单词字符 [A-Za-z0-9_] / 非
/\s/ \S/       // 空白 / 非空白
/./            // 任意字符(除换行,除非 s 标志)
/^ $/          // 首尾(m 标志下是行首尾)
/a*/           // 0 次或多次(贪婪)
/a+?/          // 1 次或多次(懒惰)
/a??/          // 0 或 1 次(懒惰)
/a{3}/         // 恰好 3 次
/a{2,4}/       // 2 到 4 次
/(ab)+/        // 分组(可捕获)
/(?:ab)+/      // 非捕获分组
/(?<name>ab)/  // 命名分组
/a(?=b)/       // 正向先行断言:a 后面是 b
/a(?!b)/       // 负向先行
/\b/           // 单词边界

贪婪 vs 懒惰:默认贪婪(尽量多吃),加 ? 变懒惰(尽量少吃):

js
'<b>粗体</b>'.match(/<.+>/);     // ['<b>粗体</b>']——贪婪吃到最后一个 >
'<b>粗体</b>'.match(/<.+?>/);    // ['<b>']——懒惰匹配到第一个 >

3.4 实战校验

js
// 常用正则(够用就好,别追求 100% 符合 RFC)
const PATTERNS = {
  mobile: /^1[3-9]\d{9}$/,
  email: /^[\w.-]+@[\w-]+(\.[\w-]+)+$/,
  idCard: /(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/,
  url: /^https?:\/\/[\w-]+(\.[\w-]+)+(\S*)?$/,
  strongPwd: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,20}$/,   // 大小写+数字,8-20 位
  ipv4: /^(\d{1,3}\.){3}\d{1,3}$/,
};

// 中文/特殊字符过滤
const onlyChinese = /^[\u4e00-\u9fa5]+$/;
'中文abc'.replace(/[^\u4e00-\u9fa5]/g, '');   // '中文'

手机号正则的坑:号段会新增,写死 13\d{9} 迟早漏号段,1[3-9]\d{9} 宽松些;更可靠的方式是发短信验证码让用户自证。邮箱正则同理——"能过 basic 检查 + 发验证邮件"比"完美 RFC 5322 正则"实用得多,后者一行能写 200 字符还没法维护。

3.5 性能与安全

  • 灾难性回溯:嵌套量词如 /(a+)+b/ 匹配 'aaaaaaaaaaaaaaaaaaaa'(无 b)会卡死浏览器。避免量词套量词,(?=...) 断言的重复也是雷区
  • 用户输入的正则要加超时/长度限制(或干脆不开放这个能力)
  • 简单 indexOf/startsWith 能做的别上正则——可读性和性能都好

四、JSON 对象

4.1 stringify 与 parse

js
const data = { name: '甲', tags: ['a', 'b'], created: new Date() };

JSON.stringify(data);
// '{"name":"甲","tags":["a","b"],"created":"2024-10-22T00:00:00.000Z"}'

JSON.stringify(data, null, 2);      // 缩进 2 空格,调试/落盘用
JSON.stringify({ a: 1, b: 2 }, ['a']);   // 数组形式 replacer:只保留 a
JSON.stringify({ a: 1, b: 2 }, (k, v) => typeof v === 'number' ? v * 2 : v);
// '{"a":2,"b":4}'——函数形式 replacer 可改造

JSON.parse('{"a":1}');              // { a: 1 }
JSON.parse('{"a":1}', (k, v) => typeof v === 'number' ? v + 1 : v);   // reviver:{ a: 2 }

// toJSON:对象自定义序列化产物
const file = { name: 'x.txt', _content: '...', toJSON() { return { name: this.name }; } };
JSON.stringify(file);   // '{"name":"x.txt"}'——_content 不输出

undefined、函数、Symbol 值的键会被丢弃;NaN/Infinity 变 null;Date 调 toJSON 出 ISO 字符串;循环引用抛 TypeError: Converting circular structure to JSON。

4.2 深拷贝与兼容

js
// JSON 深拷贝:快且无依赖,但丢函数/undefined/Symbol/Map/Set/循环引用
const copy = JSON.parse(JSON.stringify(data));

// 现代方案:structuredClone 保留更多类型(见对象篇)

JSON 法做深拷贝只适合"纯数据"(接口回来的对象正合适),带方法、类实例、日期的不要用。

4.3 安全解析

JSON.parse 比 eval 安全(不会执行代码),但不要信来源:

js
// 1. 解析可能失败——包 try/catch 或给默认值
function safeParse(str, fallback = null) {
  try {
    return JSON.parse(str);
  } catch {
    return fallback;
  }
}

// 2. localStorage 里的数据可能被用户改坏
const raw = localStorage.getItem('settings');
const settings = safeParse(raw, { theme: 'light' });   // 别裸信

// 3. 校验结构而不只是解析成功
if (settings && typeof settings.theme === 'string') {
  applyTheme(settings.theme);
}

localStorage 是用户可编辑的:把"是否 VIP""余额"存 localStorage 再读出来判断权限,等于把钥匙挂在门上。鉴权信息放 HttpOnly Cookie 或服务端会话。

五、实战:表单校验小函数

把四个对象串起来,一个能直接粘走的注册校验:

js
const RULES = {
  name: { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_-]{2,20}$/, msg: '2-20 位中英文数字' },
  mobile: { pattern: /^1[3-9]\d{9}$/, msg: '手机号格式不对' },
  password: { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,20}$/, msg: '8-20 位且含大小写和数字' },
};

function validate(form) {
  const errors = {};
  for (const [field, rule] of Object.entries(RULES)) {
    const value = (form[field] ?? '').trim();
    if (!rule.pattern.test(value)) errors[field] = rule.msg;
  }
  return errors;
}

// 密码强度:用 Math 和字符串方法
function pwdStrength(pwd) {
  let score = 0;
  score += Math.min(pwd.length, 12) / 12;                 // 长度
  if (/[a-z]/.test(pwd)) score += 0.25;
  if (/[A-Z]/.test(pwd)) score += 0.25;
  if (/\d/.test(pwd)) score += 0.25;
  if (/[^\w]/.test(pwd)) score += 0.25;
  return Math.floor(score * 100);                          // 0-100
}
pwdStrength('Abcd1234!');   // 91

六、常见坑速查

写法结果原因
new Date(2024, 10, 1)11 月 1 日月份从 0 开始
new Date('2024-10-22').getDate()可能是 21 或 22无时间部分按 UTC 解析
Math.round(-4.5)-4.5 不总向远离零方向
Math.random() 做 token可预测伪随机,安全场景用 crypto
/(\d)/g 连续两次 .test()第二次 falseg 标志记住 lastIndex
sort(() => Math.random() - 0.5)不均匀洗牌比较函数不一致
JSON.stringify(undefined)undefined(不是字符串)顶层原始值直接返回
JSON.parse('[undefined]')抛错JSON 没有 undefined
new Boolean(false) 进 if恒真对象包装,见对象篇

相关阅读

CTO Plus技术栈 Version 1.0.20261024-12