Arrays · 数组
Arrays hold lists
- An array is an ordered list of values in
[ ... ]. - Reach an item by its index, counting from
0:arr[0]is the first. .lengthtells you how many items there are.
数组存放列表
- 数组(array)是放在
[ ... ]里的一串有序的值。 - 用索引(index)取出元素,从
0开始数:arr[0]是第一个。 .length告诉你有多少个元素。
let nums = [10, 20, 30];
console.log(nums[0]); // → 10
console.log(nums.length); // → 3
Add and remove items
.push(x)addsxto the end;.pop()removes the last item.- The array grows and shrinks as you go.
添加和删除元素
.push(x)把x加到末尾;.pop()删除最后一个元素。- 数组会随之变长或变短。
let nums = [10, 20, 30];
nums.push(40);
console.log(nums); // → [10,20,30,40]
nums.pop();
console.log(nums); // → [10,20,30]
Index, push and pop · 索引、push 与 pop
Items are numbered from 0. push adds to the end; pop removes from the end. · 元素从 0 开始编号。push 加到末尾;pop 从末尾删除。
Loop over an array
- A
forloop with an index visits each item, from0tolength - 1.
遍历数组
- 带索引的
for循环依次访问每个元素,从0到length - 1。
let nums = [1, 2, 3];
for (let i = 0; i < nums.length; i++) {
console.log(nums[i]); // → 1, then 2, then 3
}
Common mistakes
- Index from
0;a.lengthis the size. pushadds to the end;popremoves from the end.
常见错误
- 从
0开始索引;a.length是长度。 push在末尾添加;pop从末尾移除。
Now you try
- Use an index, or a loop, on each array.
- Press Check answer to test it.
现在轮到你
- 对每个数组使用索引或循环。
- 按检查答案来测试它。
let colours = ["red", "green", "blue"]. Log the second item, colours[1] (it is green). · let colours = ["red", "green", "blue"]。打印第二个元素 colours[1](是 green)。
Click Run to see the output here. · 点击“运行”查看此处输出。
let nums = [4, 8, 15, 16]. Log how many items it has with .length (it is 4). · let nums = [4, 8, 15, 16]。用 .length 打印它有多少个元素(是 4)。
Click Run to see the output here. · 点击“运行”查看此处输出。
let stack = [1, 2]. Use .push to add 3, then log the array (it is [1,2,3]). · let stack = [1, 2]。用 .push 加上 3,然后打印这个数组(是 [1,2,3])。
Click Run to see the output here. · 点击“运行”查看此处输出。
Use a for loop to add up every number in nums and log the total (it is 43). · 用 for 循环把 nums 中的每个数字加起来,打印总和(是 43)。
Click Run to see the output here. · 点击“运行”查看此处输出。