let fruits = ["apple", "banana", "cherry"];
// For loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// For...of loop (ES6)
for (let fruit of fruits) {
console.log(fruit);
}
// Array.forEach() method
fruits.forEach((fruit) => {
console.log(fruit);
});
xxxxxxxxxx
var colors = ["red","blue","green"];
for (var i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
xxxxxxxxxx
var arr = ["f", "o", "o", "b", "a", "r"];
for(var i in arr){
console.log(arr[i]);
}
xxxxxxxxxx
/* ES6 */
const cities = ["Chicago", "New York", "Los Angeles"];
cities.map(city => {
console.log(city)
})
xxxxxxxxxx
const scores = [22, 54, 76, 92, 43, 33];
for (i in scores) {
console.log(scores[i]);
}
// will return
// 22
// 54
// 76
// 92
// 43
// 33
xxxxxxxxxx
//function arrayLooper will loop through the planets array
const planets = ["Mercury", "Venus", "Earth", "Mars"];
const arrayLooper = (array) => {
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
};
arrayLooper(planets);
xxxxxxxxxx
let arbitraryArr = [1, 2, 3];
// below I choose let, but var and const can also be used
for (let arbitraryElementName of arbitraryArr) {
console.log(arbitraryElementName);
}
xxxxxxxxxx
let Hello = ['Hi', 'Hello', 'Hey'];
for(let i = 0; i < Hello.length; i++) {
console.log(Hello[i]); // -> Hi Hello Hey
}
xxxxxxxxxx
let exampleArray = [1,2,3,4,5]; // The array to be looped over
// Using a for loop
for(let i = 0; i < exampleArray.length; i++) {
console.log(exampleArray[i]); // 1 2 3 4 5
}
xxxxxxxxxx
var data = [1, 2, 3, 4, 5, 6];
// traditional for loop
for(let i=0; i<=data.length; i++) {
console.log(data[i]) // 1 2 3 4 5 6
}
xxxxxxxxxx
const scores = [22, 54, 76, 92, 43, 33];
for (let i = 0; i < scores.length; i++) {
console.log(scores[i]);
}
// will return
// 22
// 54
// 76
// 92
// 43
// 33