es6 iterate array code example
Example 1: javascript iterate array
let array = ['Item 1', 'Item 2', 'Item 3'];
// Here's 4 different ways
for (let index = 0; index < array.length; index++) {
console.log(array[index]);
}
for (let index in array) {
console.log(array[index]);
}
for (let value of array) {
console.log(value); // Will log each value
}
array.forEach((value, index) => {
console.log(index); // Will log each index
console.log(value); // Will log each value
});
Example 2: javascript loop through array of objects es6
/* new options with IE6: loop through array of objects */
const people = [
{id: 100, name: 'Vikash'},
{id: 101, name: 'Sugam'},
{id: 102, name: 'Ashish'}
];
// using for of
for (let persone of people) {
console.log(persone.id + ': ' + persone.name);
}
// using forEach(...)
people.forEach(person => {
console.log(persone.id + ': ' + persone.name);
});
// output of above two methods
// 100: Vikash
// 101: Sugam
// 102: Ashish
// forEach(...) with index
people.forEach((person, index) => {
console.log(index + ': ' + persone.name);
});
// output of above code in console
// 0: Vikash
// 1: Sugam
// 2: Ashish
Example 3: loop through arrays in es6
var sandwiches = [
'tuna',
'ham',
'turkey',
'pb&j'
];
sandwiches.forEach(function (sandwich, index) {
console.log(index);
console.log(sandwich);
});
// returns 0, "tuna", 1, "ham", 2, "turkey", 3, "pb&j"
Example 4: javascript iterate array
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray)
{
// Do something
}