let arr =[1,2,3]// forEach accepts a function, and each value in array is passed to the // function. You define the function as you would any regular// function, you're just doing it inside the forEach loop
arr.forEach(function(value){console.log(value)})// you also have access to the index and original array:
arr.forEach(function(value, idx, array){console.log(idx, value, array)})// it's common for the arrow notation to be used: it's effectively// the same thing but the function keyword is removed and the syntax is// a bit different
arr.forEach((value)=>{console.log(value)})
var stringArray =["first","second"];
myArray.forEach((string, index)=>{var msg ="The string: "+ string +" is in index of "+ index;console.log(msg);// Output:// The string: first is in index of 0// The string: second is in index of 1});
var array =["a","b","c"];// example 1for(var value of array){console.log(value);
value +=1;}// example 2
array.forEach((item, index)=>{console.log(index, item)})
const arr =["some","random","words"]
arr.forEach((word)=>{// takes callback and returns undefinedconsole.log(word)})/* will print:
some
random
words */
var counter =newCounter();var numbers =[1,2,3];var sum =0;
numbers.forEach(function(e){
sum += e;this.increase();}, counter);console.log(sum);// 6console.log(counter.current());// 3Code language:JavaScript(javascript)
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)//})
angular.forEach(obj1.results,function(result1){
angular.forEach(obj2.results,function(result2){if(result1.Value=== result2.Value){//do something}});});//exact same with a for loopfor(var i =0; i < obj1.results.length; i++){for(var j =0; j < obj2.results.length; j++){if(obj1.results[i].Value=== obj2.results[j].Value){//do something}}}
const colors =['green','yellow','blue'];
colors.forEach((item, index)=>console.log(index, item));// returns the index and the every item in the array// 0 "green"// 1 "yellow"// 2 "blue"