Arrays · Array
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 menyimpan daftar
- Array adalah daftar nilai berurutan dalam
[ ... ]. - Akses item berdasarkan indeks-nya, dihitung mulai dari
0:arr[0]adalah item pertama. .lengthmemberitahu Anda berapa banyak item yang ada.
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.
Menambah dan menghapus item
.push(x)menambahkanxke akhir;.pop()menghapus item terakhir.- Array membesar dan mengecil seiring Anda berjalan.
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, dan pop
Items are numbered from 0. push adds to the end; pop removes from the end. · Item dinomori mulai dari 0. push menambah di akhir; pop menghapus dari akhir.
Loop over an array
- A
forloop with an index visits each item, from0tolength - 1.
Mengulang array
- Perulangan
fordengan indeks mengunjungi setiap item, dari0hinggalength - 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.
Kesalahan umum
- Indeks dimulai dari
0;a.lengthadalah ukuran. pushmenambahkan ke akhir;popmenghapus dari akhir.
Now you try
- Use an index, or a loop, on each array.
- Press Check answer to test it.
Sekarang Anda coba
- Gunakan indeks atau perulangan pada setiap array.
- Tekan Cek jawaban untuk mengujinya.
let colours = ["red", "green", "blue"]. Log the second item, colours[1] (it is green). · let colours = ["red", "green", "blue"]. Log item kedua, colours[1] (yaitu green).
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
let nums = [4, 8, 15, 16]. Log how many items it has with .length (it is 4). · let nums = [4, 8, 15, 16]. Log berapa banyak item yang dimilikinya dengan .length (yaitu 4).
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
let stack = [1, 2]. Use .push to add 3, then log the array (it is [1,2,3]). · let stack = [1, 2]. Gunakan .push untuk menambahkan 3, lalu log array (yaitu [1,2,3]).
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Use a for loop to add up every number in nums and log the total (it is 43). · Gunakan loop for untuk menjumlahkan semua angka dalam nums dan log totalnya (yaitu 43).
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.