Friday, March 30, 2018

Array with loop

Some types of for loop is there to iterate an array element. Let see one by one.

1. Classical for loop

2. for..of loop

3. for..in loop


Example for classical for loop.


let arrayExampleLoop = ["Apple", "Orange", "Pear"];

for (let i = 0; i < arr.length; i++) {
  alert( arrayExampleLoop[i] );
}


 Example for for..of loop:


let fruitsForOfLoop = ["Apple", "Orange", "Plum"];

// iterates over array elements
for (let fruit of fruitsForOfLoop) {
  alert( fruit );
}


Example for for...in loop:



let arrForInLoop = ["Apple", "Orange", "Pear"];

for (let key in arrForInLoop) {
  alert( arrForInLoop[key] ); // Apple, Orange, Pear
}

For arrays , we should not use for..in loop(performance issue) . But for objects you can go.








No comments:

Post a Comment