1 内置对象概述

JavaScript 提供了大量内置对象(Built-in Objects)和全局 API,无需 new 或引入即可直接使用。这些对象是 JS 语言和运行环境的核心工具,帮助我们处理数字、字符串、日期、正则、错误等常见场景。

分类

  • 包装对象:Number、String、Boolean
  • 核心对象:Object、Array、Function
  • 工具对象:Math、Date、RegExp、Error
  • 全局对象与 API:JSON、console、setTimeout 等

2 包装对象(Number / String / Boolean)

这些对象让原始值拥有方法和属性(自动装箱)。

2.1 Number

Number.MAX_VALUE;      // 最大值
Number.MIN_VALUE;      // 最小值
Number.isNaN(NaN);     // true(推荐写法)
(3.14159).toFixed(2);  // "3.14"

2.2 String

"hello".length;                    // 5
"hello".toUpperCase();             // "HELLO"
"hello".includes("ll");            // true
"hello".split("");                 // ['h','e','l','l','o']

2.3 Boolean

基本用处较少,主要通过 Boolean() 进行类型转换。

3 核心对象

3.1 Object

const obj = { name: "Alice" };
Object.keys(obj);          // ["name"]
Object.values(obj);        // ["Alice"]
Object.assign({}, obj);    // 浅拷贝

3.2 Array

(详见数组笔记,此处仅列常用 API)

  • push、pop、shift、unshift、splice
  • map、filter、reduce、forEach
  • includes、find、indexOf

3.3 Function

  • call、apply、bind(改变 this)
  • length(形参个数)

4 工具对象

4.1 Math(数学工具)

Math.PI;           // 3.14159...
Math.abs(-5);      // 5
Math.ceil(3.2);    // 4(向上取整)
Math.floor(3.8);   // 3(向下取整)
Math.round(3.5);   // 4(四舍五入)
Math.random();     // 0~1 随机小数
Math.max(1, 5, 3); // 5
Math.min(1, 5, 3); // 1

4.2 Date(日期时间)

const now = new Date();
now.getFullYear();     // 年
now.getMonth() + 1;    // 月(注意 +1)
now.getDate();         // 日
now.getHours();        // 时
now.getMinutes();      // 分
now.getSeconds();      // 秒

// 时间戳
Date.now();            // 当前毫秒时间戳
new Date("2026-04-28"); // 指定日期

4.3 RegExp(正则表达式)

const reg = /hello/i;          // i 忽略大小写
"hello world".match(reg);      // ["hello"]
/\d+/.test("年龄123");         // true

4.4 Error(错误处理)

throw new Error("出错了!");
try {
    // 代码
} catch (e) {
    console.error(e.message);
}

5 全局 API(常用)

  • JSON

    JSON.stringify(obj);   // 对象 → JSON 字符串
    JSON.parse(jsonStr);   // JSON 字符串 → 对象
    
  • console

    • console.log、console.warn、console.error、console.table
  • 定时器

    setTimeout(() => {}, 1000);   // 延时执行
    setInterval(() => {}, 1000);  // 循环执行
    clearTimeout / clearInterval  // 清除
    
  • 其他常用全局对象

    • isNaN()、parseInt()、parseFloat()
    • encodeURI、decodeURI
    • window(浏览器环境全局对象)