Objects · 对象
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Objects group related data
- An object stores named values together:
{ key: value, ... }. - Reach a value by its key with a dot:
person.name. - An object is perfect for one thing that has several details.
中文
对象把相关数据组织起来
- 对象(object)把带名字的值放在一起:
{ key: value, ... }。 - 用点号按键取出一个值:
person.name。 - 对象最适合表示一个有多个细节的事物。
let person = { name: "Ada", age: 36 };
console.log(person.name); // → Ada
console.log(person.age); // → 36
Explore · 探索
A key looks up a value · 用键查出一个值
An object maps each key · 键 to a value · 明暗. obj.key looks one up instantly. · 对象把每个键映射到一个值。obj.key 立刻查出对应的值。
English
Change or add a property
- Assign to
obj.keyto change a value — or to add a brand-new one.
中文
修改或新增属性
- 给
obj.key赋值,可以改变它的值 —— 或者新增一个全新的键。
let car = { speed: 0 };
car.speed = 60; // change an existing key
car.colour = "red"; // add a new key
console.log(car.speed); // → 60
English
Watch out
- A missing key gives
undefined, not an error:person.height→undefined. person["name"]does the same asperson.name— handy when the key sits in a variable.
中文
注意
- 不存在的键给出
undefined,而不是报错:person.height→undefined。 person["name"]和person.name效果一样 —— 当键存在变量里时很方便。
English
Common mistakes
- Read a value with
obj.keyorobj["key"]. - A missing key gives
undefined, not an error.
中文
常见错误
- 用
obj.key或obj["key"]读取值。 - 键不存在会得到
undefined,而不是报错。
English
Now you try
- Read and change object properties.
- Press Check answer to test it.
中文
现在轮到你
- 读取并修改对象的属性。
- 按检查答案来测试它。
let book = { title: "CS", pages: 200 }. Log the book's title with book.title (it is CS). · let book = { title: "CS", pages: 200 }。用 book.title 打印书的 title(是 CS)。
Click Run to see the output here. · 点击“运行”查看此处输出。
let car = { speed: 0 }. Change car.speed to · 到 80, then log it. · let car = { speed: 0 }。把 car.speed 改成 80,然后打印它。
Click Run to see the output here. · 点击“运行”查看此处输出。
Create an object p with a property x set to 3 and a property y set to 4. · 创建一个对象 p,属性 x 设为 3,属性 y 设为 4。
Click Run to see the output here. · 点击“运行”查看此处输出。