Skip to content

对象

学习如何对象分组 related 数据使用键 and 值 — 大多数常见方式到 结构信息.

你将学到

  • 什么对象是 and 为什么我们 use 它们
  • 如何 读取 and 编写属性使用点 and bracket notation
  • 如何 添加方法 (函数) 到对象
  • 如何对象 and 数组组合到 model 真实数据

概念讲解

对象

An object is a collection of key-value pairs. While arrays are good for ordered lists, objects are good for describing a *thing* with named attributes. A user has a name, an age, and an email — an object groups those together.

Creating and Accessing

const user = {
  name: "Ada",
  age: 36,
  email: "ada@示例.com",
};

user.name;        // "Ada"   — dot notation
user["age"];      // 36      — bracket notation

Use dot notation when you know the key name at write time. Use bracket notation when the key is dynamic (stored in a variable).

Adding and Updating Properties

user.isAdmin = true;     // add a new property
user.age = 37;           // update an existing one

Methods

A property whose value is a function is called a method. Methods let an object carry behavior alongside its data:

const counter = {
  count: 0,
  increment() { this.count++; },
  reset() { this.count = 0; },
};
counter.increment();
counter.increment();
console.log(counter.count);  // 2

Objects + Arrays

Real-world data usually mixes the two. A list of users is an array of objects:

const users = [
  { name: "Ada", role: "admin" },
  { name: "Grace", role: "editor" },
];

This is exactly the shape of JSON returned by most APIs — which is why understanding objects is essential for web development.

示例代码

              const product = {
  id: 42,
  name: "Wireless Mouse",
  price: 29.99,
  inStock: true,
  tags: ["electronics", "accessory"],
};

// Read properties:
console.log(product.name);            // "Wireless Mouse"
console.log(product["price"]);        // 29.99

// Update and add:
product.price = 24.99;                // sale price
product.discount = "20% off";

// Loop over keys with Object.keys:
for (const key of Object.keys(product)) {
  console.log(key, ":", product[key]);
}
            

这个 product 对象 mixes 字符串, 数字, 布尔值, and 数组. 对象.键返回键 names 所以我们能 iterate over 每个属性.

动手试一试

  • JSON Formatter

    JSON 是制作的 对象 and 数组. 粘贴 product 对象 and see 结构 visualized.

  • JSON 到 TypeScript

    Turn 对象到 TypeScript 接口 — see 如何类型描述对象 shapes.

常见错误

错误写法

Using 点 notation 使用动态键 存储 in 变量.

正确做法

Use bracket notation: obj[键], 不 obj.键. 点表单 looks for literal 属性 named '键'.

错误写法

Confusing 数组 (有序, indexed 通过数字) 使用对象 (unordered, keyed 通过 name).

正确做法

Use 数组 for 有序列表的 相似项. Use 对象 for named attributes 的单个 entity. Mix 它们当 你需要列表的 entities.

相关代码片段

练习 对象

12 个练习

练习 对象

查阅不认识的术语

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

查看术语表

动手做项目

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

查看项目

解读错误信息

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

查看错误