const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
// Iterate over fruits below
// Normal way
fruits.forEach(function(fruit){
console.log('I want to eat a ' + fruit)
});
var array = ["a","b","c"];
// example 1
for(var value of array){
console.log(value);
value += 1;
}
// example 2
array.forEach((item, index)=>{
console.log(index, item)
})
const names=["shirshak", "John","Amelia"]
//forEach is only for array and slower then for loop and for of loop
//forEach we get function which cannot be break and continue as it is not inside
//switch or loop.
names.forEach((name,index)=> {
console.log(name,index)//
})
// array for the forEach method
let grades = [13, 12, 14, 15]
// for each loop
grades.forEach(function(grade) {
console.log(grade) // loops and logs every grade of the grades array
})
//Am goinmg to practice the next big thing, using for.each function yo tripple iontegers in an array :)
//for.each function is used to run a command on each number or string in an array
const theFigures = [2,4,5,6,7,8,9,12,23,45,68,31,90];
const afterMath = (num) => {
const theArray = [];
num.forEach((n) => {
const trippled = n*3;
theArray.push(trippled);
});
return theArray;
}
console.log(afterMath(theFigures));
<p>forEach() calls a function for each element in an array:</p>
<p>Multiply the value of each element with 10:</p>
<p id="demo"></p>
<script>
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)
document.getElementById("demo").innerHTML = numbers;
function myFunction(item, index, arr) {
arr[index] = item * 10;
}
</script>
forEach() calls a function for each element in an array:
Multiply the value of each element with 10:
650,440,120,40