用数组存储多个值,用对象描述实体,然后学习如何读取和修改它们。
在 Kodokon 中打开本课到目前为止,每个变量都只保存一个值。数组是一个有序的值列表,写在方括号 [ ] 之间,各个值用逗号隔开。每个值都位于一个称为索引的编号位置上。请注意:编号从 0 开始。因此第一个元素在索引 0 处,第二个在索引 1 处,依此类推。length 属性给出元素的数量。
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // Prints: apple
console.log(fruits[2]); // Prints: cherry
console.log(fruits.length); // Prints: 3数组很容易修改。push(...) 方法在末尾添加一个元素;方法是附加在某个值上的函数,你用点号来调用它。而 fruits[0] = ... 这种写法会替换指定索引处的元素。
const fruits = ["apple", "banana"];
fruits.push("cherry"); // Adds at the end
fruits[0] = "pear"; // Replaces the first one
console.log(fruits);
// Prints: ["pear", "banana", "cherry"]对象把多个相关的信息以键: 值对的形式组织在一起,放在花括号 { } 之间。键是一个名字,就像字段的标签,值则是与之关联的数据。它非常适合用来描述日常中的实体:一个人、一件商品、一部电影……你用点号来读取或修改一个属性,例如 user.name,而且你可以随时添加新属性。
const user = {
name: "Léa",
age: 28
};
console.log(user.name); // Prints: Léa
user.age = 29; // Modifies the property
user.city = "Lyon"; // Adds a property
console.log(user.age); // Prints: 29
console.log(user.city); // Prints: Lyonfruits 的数组的第一个元素?user 对象的 name 属性?