Arrays · Arreglo
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.
อาร์เรย์เก็บรายการ
- อาร์เรย์ คือรายการที่มีลำดับของค่าใน
[ ... ] - เข้าถึงองค์ประกอบโดยใช้ ดัชนี นับเริ่มจาก
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 · Index, push และ pop
Items are numbered from 0. push adds to the end; pop removes from the end. · ไอเท็มมีเลข_label จาก 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.
ลองดูเลย
- ใช้ดัชนีหรือลูปกับแต่ละอาร์เรย์
- กด Check answer เพื่อทดสอบ
let colours = ["red", "green", "blue"]. Log the second item, colours[1] (it is green). · let colours = ["red", "green", "blue"]. บันทึก日志 รายการ项ที่ สอง, คือ colours[1] (ค่าของ nó คือ green).
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
let nums = [4, 8, 15, 16]. Log how many items it has with .length (it is 4). · let nums = [4, 8, 15, 16]. Log ว่า它有多少个ไอเท็มด้วย .length (คือ 4).
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
let stack = [1, 2]. Use .push to add 3, then log the array (it is [1,2,3]). · let stack = [1, 2]. ใช้ .push เพื่อเพิ่ม 3, แล้ว log อาร์เรย์ (คือ [1,2,3]).
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Use a for loop to add up every number in nums and log the total (it is 43). · ใช้ลูป for เพื่อรวมเลขทั้งหมดใน nums และ log ผลรวม (คือ 43).
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่