Skip to content Skip to footer

JavaScript 有哪些内置对象?

JavaScript 内置对象

JavaScript 内置对象分为三大类:值属性(并非构造函数,只是值)、函数对象(可作为构造函数)、基础对象/其他。下文按分类逐一展开。

一、值属性(全局常量)

这些是语言层面的全局常量,不是构造函数,不能 new。

对象

说明

Infinity

正无穷大

NaN

Not a Number

undefined

未定义值

globalThis

全局对象引用(浏览器中是 window,Node 中是 global)

Infinity; // Infinity

Infinity + 1; // Infinity

-Infinity; // -Infinity

NaN; // NaN

typeof NaN; // "number"

NaN === NaN; // false

undefined; // undefined

typeof undefined; // "undefined"

二、函数属性(值包装构造函数)

可将原始值转换为对应包装对象(不带 new 时是类型转换函数)。

构造函数

包装的原始值

静态方法

Object()

对象

Object.keys(), Object.values(), Object.entries(), Object.create(), Object.assign(), Object.freeze(), Object.defineProperty() 等

Function()

函数

Function.prototype.call/apply/bind

Boolean()

布尔值

Boolean()(类型转换)

Symbol()

符号

Symbol.for(), Symbol.keyFor()

Number()

数字

Number.parseInt(), Number.parseFloat(), Number.isNaN(), Number.isFinite(), Number.isInteger(), Number.MAX_SAFE_INTEGER 等

String()

字符串

String.fromCharCode(), String.fromCodePoint()

BigInt()

大整数

BigInt.asIntN(), BigInt.asUintN()

// Object 的核心静态方法

Object.keys({ a: 1, b: 2 }); // ["a", "b"]

Object.values({ a: 1, b: 2 }); // [1, 2]

Object.entries({ a: 1, b: 2 }); // [["a",1], ["b",2]]

Object.create(null); // 无原型对象

Object.freeze({ a: 1 }); // 冻结对象

Object.defineProperty(obj, key, descriptor); // 精确定义属性

// Number 的核心静态方法

Number.isNaN(NaN); // true

Number.isFinite(42); // true

Number.isInteger(42); // true

Number.parseInt("42px"); // 42

Number.isSafeInteger(42); // true

Number.MAX_SAFE_INTEGER; // 9007199254740991

Number.EPSILON; // 2.220446049250313e-16

// BigInt 静态方法

BigInt(9007199254740993); // 9007199254740993n(不丢精度)

BigInt.asIntN(8, 300n); // 44n(截断为 8 位有符号整数)

BigInt.asUintN(8, 300n); // 44n(截断为 8 位无符号整数)

三、基础对象

3.1 Object

所有对象的根基,原型链的顶端(null 除外)。

// 原型链顶端

[] instanceof Object; // true

"hello" instanceof Object; // false(原始值)

new String("hello") instanceof Object; // true

// Object.prototype 上的方法(所有对象继承)

let obj = { a: 1 };

obj.toString(); // "[object Object]"

obj.valueOf(); // { a: 1 }

obj.hasOwnProperty("a"); // true

obj.isPrototypeOf({}); // true

3.2 Function

所有函数都是 Function 的实例。

// 函数都是 Function 的实例

function greet() {}

greet instanceof Function; // true

const arrow = () => {};

arrow instanceof Function; // true

// Function 本身也是函数

Function instanceof Function; // true(鸡生蛋问题)

// Function 构造函数(不推荐,有安全风险)

const add = new Function("a", "b", "return a + b");

add(2, 3); // 5

// 实例方法

function foo(a, b) {

return foo.bind(null, a)(b); // bind 绑定 this

}

3.3 Boolean、Number、String、BigInt、Symbol

值包装类型,原型上提供操作原始值的方法。

// String.prototype 方法

"hello".length; // 5

"hello".charAt(0); // "h"

"hello".indexOf("l"); // 2

"hello".slice(1, 3); // "el"

"hello".includes("ell"); // true

"hello".trim(); // "hello"

"hello".toUpperCase(); // "HELLO"

"hello".split("l"); // ["he", "", "o"]

"ha".repeat(3); // "hahaha"

"a-b-c".replace("-", "_"); // "a_b_c"

// Number.prototype 方法

(42).toFixed(2); // "42.00"

(3.14).toPrecision(3); // "3.14"

(255).toString(16); // "ff"

(100).toLocaleString(); // "100"

// Symbol 方法

let s = Symbol("desc");

s.description; // "desc"

typeof s; // "symbol"

3.4 Array

数组对象,最常用的内置对象之一。

// 创建

let arr = [1, 2, 3];

let arr2 = Array.of(1, 2, 3); // [1, 2, 3]

let arr3 = Array.from("hello"); // ["h", "e", "l", "l", "o"]

let arr4 = Array.from({ length: 3 }, (_, i) => i); // [0, 1, 2]

// 静态方法

Array.isArray([1]); // true

Array.from(iterable); // 从可迭代对象创建

Array.of(1, 2, 3); // 从参数创建

// 变异方法(修改原数组)

arr.push(4); // 末尾添加

arr.pop(); // 末尾删除

arr.unshift(0); // 开头添加

arr.shift(); // 开头删除

arr.splice(1, 1); // 从索引1删除1个

arr.sort((a, b) => a - b); // 排序

arr.reverse(); // 反转

arr.fill(0); // 填充

// 非变异方法(返回新数组)

arr.concat([4, 5]); // 合并

arr.slice(1, 3); // 截取

arr.map(x => x * 2); // 映射

arr.filter(x => x > 1); // 过滤

arr.reduce((acc, x) => acc + x, 0); // 累计

arr.find(x => x > 1); // 查找

arr.findIndex(x => x > 1); // 查找索引

arr.every(x => x > 0); // 全部满足?

arr.some(x => x > 2); // 有满足的?

arr.flat(); // 扁平化

arr.flatMap(x => [x, x]); // 映射+扁平化

arr.keys(); // 键迭代器

arr.values(); // 值迭代器

arr.entries(); // 条目迭代器

[...arr]; // 展开为数组

// 查找

arr.indexOf(2); // 索引

arr.includes(2); // 是否包含

3.5 Date

日期时间处理。

let now = new Date();

// 获取

now.getFullYear(); // 年

now.getMonth(); // 月(0-11,注意从0开始)

now.getDate(); // 日

now.getHours(); // 时

now.getMinutes(); // 分

now.getSeconds(); // 秒

now.getMilliseconds(); // 毫秒

now.getDay(); // 星期(0=周日)

now.getTime(); // 时间戳(毫秒)

now.getTimezoneOffset(); // 时区偏移(分钟)

// 格式化

now.toISOString(); // "2026-06-23T..."

now.toLocaleDateString(); // "2026/6/23"

now.toLocaleString(); // "2026/6/23 10:00:00"

// 解析

Date.parse("2026-06-23"); // 时间戳

Date.now(); // 当前时间戳

// 静态方法

Date.now(); // 当前时间戳

Date.UTC(2026, 5, 23); // UTC 时间戳

四、错误对象

所有错误对象的基类,可被 throw 抛出,try...catch 捕获。

错误类型

触发场景

Error

通用错误基类

SyntaxError

语法错误

ReferenceError

引用未声明的变量

TypeError

类型操作错误(如对 null 调用方法)

RangeError

值超出有效范围

URIError

encodeURI/decodeURI 等失败

EvalError

eval() 执行错误(已很少使用)

AggregateError

多个错误的集合(Promise.any 使用)

// 创建

const err = new Error("出错了");

err.name; // "Error"

err.message; // "出错了"

err.stack; // 调用堆栈

// 抛出和捕获

try {

throw new TypeError("类型错误");

} catch (e) {

if (e instanceof TypeError) { ... }

if (e instanceof RangeError) { ... }

}

// AggregateError

try {

Promise.any([

Promise.reject(new Error("A")),

Promise.reject(new Error("B"))

]);

} catch (e) {

// e 是 AggregateError

e.errors; // [Error: A, Error: B]

}

五、集合与映射

5.1 Map

键值对映射,键可以是任意类型。

let map = new Map([

["name", "张三"],

[{ a: 1 }, "对象键"],

[42, "数字键"]

]);

map.set("key", "value"); // 设置

map.get("key"); // "value" 获取

map.has("key"); // true 检查

map.delete("key"); // true 删除

map.clear(); // 清空

map.size; // 3 大小

// 迭代

for (let [k, v] of map) { ... }

for (let k of map.keys()) { ... }

for (let v of map.values()) { ... }

5.2 Set

唯一值集合,自动去重。

let set = new Set([1, 2, 3, 2, 1]); // Set {1, 2, 3}

set.add(4); // 添加

set.has(2); // true 检查

set.delete(1); // 删除

set.size; // 2

// 常见用法:数组去重

[...new Set([1, 2, 2, 3, 3])]; // [1, 2, 3]

// 集合运算

let a = new Set([1, 2, 3]);

let b = new Set([2, 3, 4]);

// 并集

new Set([...a, ...b]); // Set {1, 2, 3, 4}

// 交集

new Set([...a].filter(x => b.has(x))); // Set {2, 3}

// 差集

new Set([...a].filter(x => !b.has(x))); // Set {1}

5.3 WeakMap / WeakSet

弱引用版本,键只能是对象,不可迭代。

// WeakMap

let wm = new WeakMap();

let obj = {};

wm.set(obj, "数据");

wm.get(obj); // "数据"

wm.has(obj); // true

wm.delete(obj); // true

// obj 被回收后,WeakMap 中的条目自动清除

// WeakSet

let ws = new WeakSet();

let el = document.getElementById("app");

ws.add(el);

ws.has(el); // true

ws.delete(el); // true

// 典型用途:标记已处理过的 DOM 元素

六、结构化数据

6.1 ArrayBuffer / SharedArrayBuffer

二进制数据缓冲区,固定长度。

// ArrayBuffer:固定长度的原始二进制缓冲区

let buffer = new ArrayBuffer(16); // 16 字节

buffer.byteLength; // 16

// SharedArrayBuffer:可被多个线程(Worker)共享

let shared = new SharedArrayBuffer(16);

6.2 DataView

在 ArrayBuffer 上读写任意位置和类型的二进制数据。

let buffer = new ArrayBuffer(8);

let view = new DataView(buffer);

view.setInt8(0, 42); // 在偏移 0 写入 1 字节整数

view.setFloat32(4, 3.14); // 在偏移 4 写入 4 字节浮点数

view.getInt8(0); // 42

view.getFloat32(4); // 3.14

6.3 类型化数组(TypedArray)

将 ArrayBuffer 视为特定类型的数组,提供结构化的二进制数据访问。

类型化数组

元素大小

等价 C 类型

Int8Array

1 字节

int8_t

Uint8Array

1 字节

uint8_t

Uint8ClampedArray

1 字节

uint8_t(溢出截断为 0~255)

Int16Array

2 字节

int16_t

Uint16Array

2 字节

uint16_t

Int32Array

4 字节

int32_t

Uint32Array

4 字节

uint32_t

Float32Array

4 字节

float

Float64Array

8 字节

double

BigInt64Array

8 字节

int64_t

BigUint64Array

8 字节

uint64_t

let buffer = new ArrayBuffer(16);

let int8 = new Int8Array(buffer); // 16 个 int8

let int32 = new Int32Array(buffer); // 4 个 int32

let float64 = new Float64Array(buffer); // 2 个 float64

// 共享同一 buffer,修改一个会影响另一个

int8[0] = 42;

int32[0]; // 42(同一个字节)

// 从数组创建

let arr = new Int32Array([1, 2, 3, 4]);

arr[0]; // 1

arr.length; // 4

arr.BYTES_PER_ELEMENT; // 4

// 常见用途

// 1. Canvas 图像处理

let imageData = new Uint8ClampedArray(canvas.width * canvas.height * 4);

// 2. WebSocket 二进制通信

socket.binaryType = "arraybuffer";

// 3. 文件读取

fileReader.readAsArrayBuffer(file);

6.4 JSON

JSON 解析与序列化。

// 序列化

JSON.stringify({ a: 1, b: "hello" }); // '{"a":1,"b":"hello"}'

JSON.stringify({ a: undefined }); // '{}'

JSON.stringify({ a: null }); // '{"a":null}'

JSON.stringify({ a: NaN }); // '{"a":null}'

// 美化输出

JSON.stringify({ a: 1 }, null, 2);

// {

// "a": 1

// }

// 反序列化

JSON.parse('{"a":1,"b":"hello"}'); // { a: 1, b: "hello" }

// 带转换函数

JSON.parse('{"a":1,"b":"2"}', (key, value) => {

if (key === "b") return Number(value);

return value;

}); // { a: 1, b: 2 }

七、控制抽象对象

7.1 Promise

异步操作的标准容器。

// 创建

let promise = new Promise((resolve, reject) => {

setTimeout(() => resolve("成功"), 1000);

});

// 静态方法

Promise.resolve(42); // 已成功的 Promise

Promise.reject(new Error()); // 已失败的 Promise

Promise.all([p1, p2]); // 全部成功才成功

Promise.allSettled([p1, p2]); // 全部完成后返回每个结果

Promise.race([p1, p2]); // 第一个完成(无论成功失败)

Promise.any([p1, p2]); // 第一个成功

// 实例方法

promise.then(value => { ... });

promise.catch(error => { ... });

promise.finally(() => { ... });

// 链式调用

fetch("/api")

.then(res => res.json())

.then(data => processData(data))

.catch(err => handleError(err))

.finally(() => hideLoading());

7.2 Generator

可暂停/恢复的函数。

function* gen() {

yield 1;

yield 2;

yield 3;

}

let g = gen();

g.next(); // { value: 1, done: false }

g.next(); // { value: 2, done: false }

g.next(); // { value: 3, done: false }

g.next(); // { value: undefined, done: true }

// 惰性求值

function* range(start, end) {

for (let i = start; i < end; i++) yield i;

}

[...range(0, 5)]; // [0, 1, 2, 3, 4]

7.3 AsyncFunction / AsyncGenerator

async/await 语法创建的函数。

// AsyncFunction(async function)

async function fetchData() {

let res = await fetch("/api");

let data = await res.json();

return data;

}

// 返回 Promise

// AsyncGenerator(async function*)

async function* streamData(url) {

let response = await fetch(url);

let reader = response.body.getReader();

while (true) {

let { done, value } = await reader.read();

if (done) break;

yield value;

}

}

八、反射

8.1 Reflect

统一的元操作 API,将 Object 上一些命令式的操作改为函数式调用。

Reflect.apply(target, thisArg, args); // 等价于 Function.prototype.apply

Reflect.construct(target, args, newTarget); // 等价于 new target(...args)

Reflect.get(obj, key, receiver); // 等价于 obj[key]

Reflect.set(obj, key, value, receiver); // 等价于 obj[key] = value

Reflect.has(obj, key); // 等价于 key in obj

Reflect.deleteProperty(obj, key); // 等价于 delete obj[key]

Reflect.ownKeys(obj); // 等价于 Object.keys + getOwnPropertySymbols

Reflect.getPrototypeOf(obj); // 等价于 Object.getPrototypeOf

Reflect.setPrototypeOf(obj, proto); // 等价于 Object.setPrototypeOf

Reflect.defineProperty(obj, key, descriptor); // 等价于 Object.defineProperty

Reflect.isExtensible(obj); // 等价于 Object.isExtensible

Reflect.preventExtensions(obj); // 等价于 Object.preventExtensions

Reflect.getOwnMetadata(metadataKey, obj); // 获取自定义元数据

// 与 Proxy 配合使用

let proxy = new Proxy(target, {

get(target, key, receiver) {

console.log(`读取 ${key}`);

return Reflect.get(target, key, receiver);

}

});

8.2 Proxy

拦截并自定义对象的基本操作。

let handler = {

get(target, key) {

console.log(`读取属性: ${key}`);

return target[key];

},

set(target, key, value) {

console.log(`设置属性: ${key} = ${value}`);

target[key] = value;

return true;

},

has(target, key) {

console.log(`检查属性: ${key}`);

return key in target;

},

deleteProperty(target, key) {

console.log(`删除属性: ${key}`);

return delete target[key];

}

};

let obj = { name: "张三" };

let proxy = new Proxy(obj, handler);

proxy.name; // "读取属性: name" → "张三"

proxy.age = 25; // "设置属性: age = 25"

"name" in proxy; // "检查属性: name" → true

可拦截的操作(共 13 种 trap):

trap

拦截的操作

get

属性读取

set

属性设置

has

in 操作符

deleteProperty

delete 操作符

getOwnPropertyDescriptor

Object.getOwnPropertyDescriptor

defineProperty

Object.defineProperty

getPrototypeOf

Object.getPrototypeOf

setPrototypeOf

Object.setPrototypeOf

isExtensible

Object.isExtensible

preventExtensions

Object.preventExtensions

ownKeys

Object.keys/entries/values/getOwnPropertyNames

apply

函数调用

construct

new 操作

九、国际化

9.1 Intl

国际化 API 命名空间,包含多个子对象。

// Intl.DateTimeFormat —— 日期格式化

new Intl.DateTimeFormat("zh-CN", {

year: "numeric", month: "long", day: "numeric"

}).format(new Date()); // "2026年6月23日"

new Intl.DateTimeFormat("en-US").format(new Date()); // "6/23/2026"

// Intl.NumberFormat —— 数字格式化

new Intl.NumberFormat("zh-CN").format(1234567.89); // "1,234,567.89"

new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })

.format(1234.56); // "$1,234.56"

new Intl.NumberFormat("zh-CN", { style: "percent" }).format(0.85); // "85%"

// Intl.RelativeTimeFormat —— 相对时间

new Intl.RelativeTimeFormat("zh-CN").format(-1, "day"); // "1天前"

new Intl.RelativeTimeFormat("en-US").format(1, "month"); // "in 1 month"

// Intl.Collator —— 字符串排序

["张三", "李四", "王五"].sort(new Intl.Collator("zh-CN").compare);

// Intl.PluralRules —— 复数规则

new Intl.PluralRules("zh-CN").select(0); // "other"

new Intl.PluralRules("zh-CN").select(1); // "one"

new Intl.PluralRules("en-US").select(0); // "other"

new Intl.PluralRules("en-US").select(1); // "one"

// Intl.ListFormat —— 列表格式化

new Intl.ListFormat("zh-CN").format(["苹果", "香蕉", "橘子"]); // "苹果、香蕉和橘子"

new Intl.ListFormat("en-US").format(["A", "B", "C"]); // "A, B, and C"

十、Web API(浏览器环境中的内置对象)

以下不属于 ECMAScript 规范,而是浏览器环境的内置对象(非 JS 语言核心,但开发中常用)。

类别

对象

说明

DOM

document, window, Node, Element, Event 等

文档对象模型

BOM

navigator, location, history, screen, localStorage, sessionStorage

浏览器对象模型

定时器

setTimeout, setInterval, requestAnimationFrame

定时执行

网络

fetch, XMLHttpRequest, WebSocket, EventSource

网络请求

事件

Event, CustomEvent, EventTarget, MessageChannel, AbortController

事件系统

Canvas

CanvasRenderingContext2D, WebGLRenderingContext

绑图

Worker

Worker, SharedWorker, BroadcastChannel

多线程

编码

btoa(), atob(), TextEncoder, TextDecoder

Base64 / 文本编码

URL

URL, URLSearchParams

URL 解析

性能

performance, PerformanceObserver, performance.now()

性能监测

Intersection

IntersectionObserver, ResizeObserver, MutationObserver

观察 API

存储

Storage, IndexedDB, caches

客户端存储

媒体

AudioContext, MediaStream, MediaRecorder

音视频

加密

crypto, SubtleCrypto

Web Crypto API

结构化

structuredClone()

深拷贝

// 常用 Web API 示例

// fetch

fetch("/api").then(res => res.json());

// localStorage

localStorage.setItem("key", "value");

localStorage.getItem("key");

// URL

let url = new URL("https://example.com/path?a=1&b=2");

url.searchParams.get("a"); // "1"

// IntersectionObserver

const observer = new IntersectionObserver(entries => {

entries.forEach(entry => {

if (entry.isIntersecting) loadContent();

});

});

observer.observe(document.getElementById("target"));

// AbortController(取消 fetch)

const controller = new AbortController();

fetch("/api", { signal: controller.signal });

controller.abort(); // 取消请求

// structuredClone(深拷贝)

structuredClone({ a: { b: 1 } }); // { a: { b: 1 } }

十一、全局函数(非构造函数)

函数

说明

parseInt()

解析整数(注意与 Number.parseInt 的区别)

parseFloat()

解析浮点数

isNaN()

非严格 NaN 判断

isFinite()

是否有限数

decodeURI() / encodeURI()

URI 编解码

decodeURIComponent() / encodeURIComponent()

URI 组件编解码

eval()

执行字符串代码(不推荐)

setTimeout() / setInterval()

定时器(Web API,非 ECMAScript)

parseInt("42px"); // 42

parseInt("0xFF", 16); // 255

parseFloat("3.14"); // 3.14

isNaN("hello"); // true ← 先 ToNumber

Number.isNaN("hello"); // false ← 严格类型

isFinite(42); // true

isFinite(Infinity); // false

encodeURI("https://example.com/路径?q=你好");

// "https://example.com/%E8%B7%AF%E5%BE%84?q=%E4%BD%A0%E5%A5%BD"

encodeURIComponent("a=1&b=2");

// "a%3D1%26b%3D2"

十二、分类速查总表

类别

内置对象

值属性

Infinity, NaN, undefined, globalThis

值包装

Object, Function, Boolean, Symbol, Number, String, BigInt

集合

Map, Set, WeakMap, WeakSet

结构化

ArrayBuffer, SharedArrayBuffer, DataView, 各 TypedArray, JSON

错误

Error, SyntaxError, ReferenceError, TypeError, RangeError, URIError, EvalError, AggregateError

日期

Date

数组

Array

控制抽象

Promise, Generator, AsyncFunction, AsyncGenerator

反射

Reflect, Proxy

正则

RegExp

数学

Math

国际化

Intl(含 DateTimeFormat, NumberFormat, Collator, PluralRules, ListFormat, RelativeTimeFormat)

十三、总结

JavaScript 内置对象可以按职责分为几大阵营:

阵营

代表对象

核心职责

值包装

Number, String, Boolean, Symbol, BigInt

为原始值提供方法和类型转换

集合映射

Map, Set, WeakMap, WeakSet

数据存储与关联

结构化二进制

ArrayBuffer, DataView, TypedArray

二进制数据操作

异步控制

Promise, Generator

异步流程与惰性求值

反射元编程

Proxy, Reflect

拦截和自定义对象行为

国际化

Intl.DateTimeFormat, Intl.NumberFormat 等

本地化格式化

工具

Math, JSON, Date, RegExp, Error

通用计算、序列化、日期、正则、错误

需要注意区分 ECMAScript 规范内置对象和浏览器 Web API——前者在 Node.js 和浏览器中都可用,后者仅在浏览器环境中存在。

Copyright © 2088 手游限时活动通 - 周末狂欢福利 All Rights Reserved.
友情链接