Loops and Iteration

Array

  • Bisa berisi primitive value
  • Bisa berisi object
  • bisa berisi function
  • bisa berisi array
  • bisa berisi campuran dari semua type.

Kumpulan segala sesuatu

Rumus:

[

]

Element1, Element2, ElementN..

0

1

index ke n

Contoh:

var buah = ["pisang", "mangga"];
console.log(buah.length)

// akses item array dengan index
var first = buah[0];
var last = buah[buah.length - 1];
console.log(first, last);

// loop using forEach
buah.forEach(function(item, index) {
  console.log(item, index);
});

// tambah item buah di akhir
buah.push("nanas");
console.log(buah)

// hapus item  terakhir pada array
buah.pop();
console.log(buah)

// hapus item pada index pertama
buah.shift();

// menambahkan item buah di awal
buah.unshift("ceri");

// cari index
buah.indexOf("pisang")

Contoh:

// hapus item array berdasarkan index
var itemYgDihapus = buah.splice(1, 1);

var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'];
console.log(vegetables); 
// ["Cabbage", "Turnip", "Radish", "Carrot"]

var pos = 1, n = 2;

var removedItems = vegetables.splice(pos, n); 

console.log(vegetables); 
// ["Cabbage", "Carrot"] (array aslinya berubah)

console.log(removedItems); 
// ["Turnip", "Radish"]


// gunakan slice untuk menyalin array dan tidak merubah array aslinya
var shallowCopy = fruits.slice();

Array methods

Apa dan Mengapa butuh perulangan?

Rangkaian instruksi yang terus diulang sampai kondisi tertentu tercapai.

  • berjalan dengan lebih efisien. contoh: menulis 1 sampai 100. lebih mudah dengan looping daripada menulis satu-satu. DRY!

Iteration

  • while loop

  • do...while loop

  • for loop

  • for...of loop

  • for...in loop

let's code

Loops and Iteration

By ikhsanalatsary

Loops and Iteration

  • 86