1var arr = ['one','two','three','four','five'];
2$.each(arr, function(index, value){
3 console.log('The value at arr[' + index + '] is: ' + value);
4});
1$( "li" ).each(function( index ) {
2 console.log( index + ": " + $( this ).text() );
3});
1const avengers = ['thor', 'captain america', 'hulk'];
2avengers.forEach((item, index)=>{
3 console.log(index, item)
4})
1//Array
2$.each( arr, function( index, value ){
3 sum += value;
4});
5
6//Object
7$.each( obj, function( key, value ) {
8 sum += value;
9});
1const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
2
3// Iterate over fruits below
4
5// Normal way
6fruits.forEach(function(fruit){
7 console.log('I want to eat a ' + fruit)
8});
1function each(collection, action) {
2 if (Array.isArray(collection)) {
3 for (var i = 0; i < collection.length; i++) {
4 action(collection[i], i, collection);
5 }
6 } else {
7 for (var key in collection) {
8 action(collection[key], key, collection);
9 }
10 }
11}