For In JavaScript

For In 循环

JavaScript for in 语句循环遍历对象的属性:

语法

for (key in object) {
  // code block to be executed
}

Contoh

const person = {fname:"Bill", lname:"Gates", age:25};
let text = "";
for (let x in person) {
  text += person[x];
}

Coba Sendiri

例子解释

  • for in 循环遍历 person 对象
  • 每次迭代返回一个 (x)
  • 键用于访问键的
  • 键的值为 person[x]

For In 遍历数组

JavaScript for in 语句也可以遍历数组的属性:

语法

for (variable in array) {
  code
}

Contoh

const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
  txt += numbers[x];
}

Coba Sendiri

Jika indeksUrutanpenting, jangan gunakan for in

Urutan indeks tergantung implementasi, mungkin tidak mengakses nilai array menurut urutan yang diharapkan.

Ketika urutan penting, paling baik digunakan for Perulangan,for of Perulangan atau Array.forEach()

Array.forEach()

forEach() Metode memanggil fungsi sekali untuk setiap elemen array (fungsi panggil kembali).

Contoh

const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value, index, array) {
  txt += value;
}

Coba Sendiri

Perhatikan, fungsi ini menggunakan 3 parameter:

  • Nilai Item
  • Indeks Item
  • Bentuk Array

Contoh di atas hanya menggunakan parameter value. Dapat diubah menjadi:

Contoh

const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value) {
  txt += value;
}

Coba Sendiri