Skip to content

JavaScript 对象

对象 as 键-值集合, 属性 access, destructuring, and spread 运算符.

你将学到

  • 创建对象使用对象 literal 语法
  • 点 notation 对比 bracket notation for 属性 access
  • 方法, computed 键, and shorthand 属性 names
  • Destructuring and spread 运算符 for 对象
  • Shallow 复制对比 deep 复制 and 为什么它 matters

概念讲解

什么是对象?

An object is a collection of key-value pairs where the keys are strings (or Symbols) and the values can be anything — primitives, arrays, functions, or other objects.

const player = {
  name: "Ada",
  level: 12,
  inventory: ["sword", "shield"],
  attack() {
    return this.level * 5;
  },
};

Accessing Properties

// Dot notation — use when the key is a valid identifier
player.name;     // "Ada"

// Bracket notation — use when the key is dynamic or not a valid identifier
const key = "level";
player[key];     // 12
player["inven" + "tory"]; // ["sword", "shield"]

Methods and this

A method is a function stored as a property. Inside a regular method, 这个 refers to the object the method was called on:

player.attack(); // 60 — this.level is 12

Shorthand and Computed Keys

const name = "Ada";
const level = 12;
const p = { name, level }; // shorthand — same as { name: name, level: level }

const dynamicKey = "score";
const obj = { [dynamicKey]: 100 }; // { score: 100 }

Destructuring

const { name, level } = player; // name="Ada", level=12
const { name: playerName } = player; // rename: playerName="Ada"

Spread and Merging

const defaults = { theme: "light", fontSize: 14 };
const userPrefs = { fontSize: 18 };
const merged = { ...defaults, ...userPrefs }; // { theme: "light", fontSize: 18 }

Shallow vs Deep Copy

The spread operator creates a shallow copy — nested objects are still shared by reference:

const original = { stats: { hp: 100 } };
const copy = { ...original };
copy.stats.hp = 0;
console.log(original.stats.hp); // 0 — shared nested object!

For a deep copy, use structuredClone(原始) (available in modern browsers and Node.js 17+).

示例代码

              // Build a user profile object
const user = {
  id: 101,
  name: "Ada Lovelace",
  role: "admin",
  permissions: ["read", "write", "delete"],
  isActive: true,
};

// Destructure the fields you need
const { name, role } = user;
console.log(`${name} is an ${role}`);

// Merge with new settings using spread
const withSettings = {
  ...user,
  settings: { theme: "dark", notifications: true },
};
console.log(withSettings.settings.theme);

// Iterate over keys and values
for (const [key, value] of Object.entries(user)) {
  console.log(`${key}: ${value}`);
}

// Shallow copy pitfall
const copy = { ...user };
copy.permissions.push("super");
console.log(user.permissions); // ["read", "write", "delete", "super"] — shared!

// Deep copy with structuredClone
const deep = structuredClone(user);
deep.permissions.pop();
console.log(user.permissions); // unchanged after deep clone edit
            

这个 demonstrates destructuring, spread 合并, 对象.条目 iteration, shallow-复制 pitfall 使用 nested 数组, and safe deep 复制使用 structuredClone.

动手试一试

  • JSON Formatter

    对象是 JSON-如 — 粘贴 and 格式它们到 inspect 结构.

  • JSON 树 Viewer

    Browse deeply nested 对象 in collapsible 树.

常见错误

错误写法

Using shallow 复制 and accidentally mutating nested 数据

正确做法

Spread ({ ...obj }) 仅复制 one level. Nested 对象 and 数组是 still shared. Use structuredClone(obj) for 真 deep 复制.

错误写法

Using 点 notation 使用动态 or 特殊-character 键

正确做法

点 notation 仅工作使用有效 identifier 键. Use bracket notation (obj[键]) 当键 是变量 or 包含特殊 characters.

相关工具

相关速查表

练习 JavaScript 对象

21 个练习

练习 JavaScript 对象

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误