js each function code example

Example 1: jquery loop over elements

$( "li" ).each(function( index ) {
  console.log( index + ": " + $( this ).text() );
});

Example 2: javascript foreach

const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
	console.log(index, item)
})

Example 3: for each js

const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

// Iterate over fruits below

// Normal way
fruits.forEach(function(fruit){
  console.log('I want to eat a ' + fruit)
});

Example 4: jquery foreach

$.each( obj, function( key, value ) {
  alert( key + ": " + value );
});

Example 5: jquery each

//Array
$.each( arr, function( index, value ){
    sum += value;
});

//Object
$.each( obj, function( key, value ) {
    sum += value;
});

Example 6: foreach javascript

let words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
  console.log(word);
});
// one
// two
// three
// four

Tags:

Php Example