Answers for "javascript foreach syntax"

120

javascript foreach

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

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
17

foreach javascript

var items = ["item1", "item2", "item3"]
var copie = [];

items.forEach(function(item){
  copie.push(item);
});
Posted by: Guest on February-27-2020
4

js foreach

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
});
Posted by: Guest on October-01-2020
-2

javascript foreach syntax

const marks = [12, 17, 14];
let sum = 0;

marks.forEach(mark => {
  sum += mark;
});
Posted by: Guest on October-31-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language