Skip to content

Objects

JavaScript Lesson 14 2:17 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
An array holds a list of similar things. 数组装的是一串同类的东西。
An object holds different facts about ONE thing. 对象装的是关于同一个事物的不同事实。
You could keep a book's title and page count in two separate variables, and nothing would stop you — but nothing connects them either, except that you gave them similar names. 你当然可以把一本书的书名和页数放在两个各自独立的变量里,也没人拦着你—— 但除了名字取得像以外,没有任何东西把它们联系起来。
Put them in one object and the book becomes a single value you can pass to a function, store in an array, or copy as one thing. 把它们放进一个对象,这本书就成了一个单独的值, 你可以把它传给函数、放进数组,或者作为一个整体复制。
Each entry is a property: a name, a colon, and a value. 每一项都是一个属性:名字、冒号、值。
To read one you write the object, a dot and the name of the property. 要读取其中一个,你写对象名、一个点,再写属性的名字。
And notice what is missing: no quotes around the name here, even though it was a name and not a variable when you wrote the object. 注意少了什么:这里名字外面没有引号, 尽管你在写这个对象时它是一个名字而不是变量。
That is the JavaScript convention, and it is why object code reads so much like ordinary English. 这是 JavaScript 的写法约定,也正因为如此,对象的代码读起来才那么像日常英语。
The same dot works on the left of an equals sign. 同样的点号也可以写在等号左边。
Assign to a property that exists and it replaces what was there — the car's speed goes from zero to eighty. 给一个已经存在的属性赋值,就会替换掉原来的内容——车的速度从 0 变成 80。
Assign to a name it has never had, and JavaScript does not complain: it adds the property. 给一个它从来没有过的名字赋值,JavaScript 也不会报错:它会新增这个属性。
That is convenient and it is also a trap, because a typo in the name silently creates a new property instead of changing the one you meant. 这既方便,也是个陷阱,因为名字打错时, 它会悄悄新建一个属性,而不是改动你本来想改的那个。
Now the lesson's third task: make a point with an x and a y. 现在做课程里的第三道题:做一个带 x 和 y 的点。
Two properties, one object, one line — and const is right here, because you are not going to replace the point itself, only read from it. 两个属性,一个对象,一行代码——这里用 const 正合适, 因为你不会去替换这个点本身,只会读取它。
Then look ahead: once you have several of them, you put the objects in an array. 再往前看一步:等你有了好几个点,就把这些对象放进一个数组。
An array of objects is how nearly every real data set you will meet is shaped. 列表套对象,几乎就是你以后遇到的每一份真实数据的样子。
Four things to take with you. 带走四点。
One: curly braces hold name-and-value pairs. 第一:花括号里放的是“名字:值”这样的成对内容。
Two: read one with a dot — book dot title. 第二:用点号读取其中一个——book.title。
Three: assigning to a new name adds that property rather than failing. 第三:给一个新名字赋值会新增那个属性,而不是报错。
Four: asking for a property that is not there is undefined, not an error, so a typo shows up as undefined further down. 第四:访问一个不存在的属性得到的是 undefined,而不是错误, 所以名字打错时,问题会以 undefined 的形式在后面才显现出来。
Now do the three tasks. 现在去做那三道题。

Log in or create account

IGCSE, A-Level & AP