Answers for "for each in javascript"

130

javascript foreach

const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
	console.log(index, item)
})
Posted by: Guest on April-27-2020
56

javascript foreach

var colors = ['red', 'blue', 'green'];

colors.forEach(function(color) {
  console.log(color);
});
Posted by: Guest on June-27-2019
6

For-each over an array in JavaScript

/** 1. Use forEach and related */
var a = ["a", "b", "c"];
a.forEach(function(entry) {
    console.log(entry);
});

/** 2. Use a simple for loop */
var index;
var a = ["a", "b", "c"];
for (index = 0; index < a.length; ++index) {
    console.log(a[index]);
}

/**3. Use for-in correctly*/
// `a` is a sparse array
var key;
var a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (key in a) {
    if (a.hasOwnProperty(key)  &&        // These checks are
        /^0$|^[1-9]\d*$/.test(key) &&    // explained
        key <= 4294967294                // below
        ) {
        console.log(a[key]);
    }
}

/** 4. Use for-of (use an iterator implicitly) (ES2015+) */
const a = ["a", "b", "c"];
for (const val of a) {
    console.log(val);
}

/** 5. Use an iterator explicitly (ES2015+) */
const a = ["a", "b", "c"];
const it = a.values();
let entry;
while (!(entry = it.next()).done) {
    console.log(entry.value);
}
Posted by: Guest on November-27-2019
35

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)
});
Posted by: Guest on March-29-2020
31

js for each item do

let array = ['Item 1', 'Item 2', 'Item 3'];

array.forEach(item => {
	console.log(item); // Logs each 'Item #'
});
Posted by: Guest on February-20-2020
33

for each java

int [] intArray = { 10, 20, 30, 40, 50 };
        
for( int value : intArray ) {
   System.out.println( value );
}
Posted by: Guest on April-13-2020

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language