Loops/Foreach: Difference between revisions

Fixed whitespace and inconsistent quotes.
(Add Plain English)
(Fixed whitespace and inconsistent quotes.)
Line 1,320:
 
=={{header|JavaScript}}==
 
For arrays in ES5, we can use '''Array.forEach()''':
<lang JavaScript>"alpha beta gamma delta".split('" '").forEach(function (x) {
 
<lang JavaScript>"alpha beta gamma delta".split(' ').forEach(
function (x) {
console.log(x);
});</lang>
}
);</lang>
 
Output:
<pre>alpha
beta
gamma
delta</pre>
 
though it will probably be more natural – dispensing with side-effects, and allowing for easier composition of nested functions – to simply use '''Array.map()''',
<lang JavaScript>console.log("alpha beta gamma delta".split('" '").map(function (x) {
 
<lang JavaScript>console.log("alpha beta gamma delta".split(' ').map(
function (x) {
return x.toUpperCase(x);
}).join('"\n'"));</lang>
}
).join('\n'));</lang>
 
Output:
 
<pre>ALPHA
BETA
GAMMA
DELTA</pre>
 
or, more flexibly, and with greater generality, obtain an accumulating fold from '''Array.reduce()'''
<lang JavaScript>console.log("alpha beta gamma delta".split('" '").reduce(function (a, x, i, lst) {
 
return lst.length - i + '". '" + x + '"\n'" + a;
<lang JavaScript>console.log(
}, ""));</lang>
"alpha beta gamma delta".split(' ').reduce(
function (a, x, i, lst) {
return lst.length - i + '. ' + x + '\n' + a;
}, ''
)
)</lang>
 
Output:
 
<pre>1. delta
2. gamma
3. beta
4. alpha</pre>
 
More generally, the following works for any object, including an array. It iterates over the keys of an object.
<lang JavaScript>for (var a in o) {
Line 1,377 ⟶ 1,342:
}
}</lang>
 
{{works with|JavaScript|1.6}}
;Deprecated
Line 1,383 ⟶ 1,347:
<lang JavaScript>h = {"one":1, "two":2, "three":3}
for (x in h) print(x);
for each (y in h) print(y);</lang>
/*
two
one
three
*/
 
for each (y in h) print(y);
/*
2
1
3
*/</lang>
 
{{works with|ECMAScript|6th edition}}
There is also a <tt>[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...of for of]</tt> construct that iterates over the values of an object:
<lang JavaScript>h = {"one":1, "two":2, "three":3}
for (x in h) print(x);
for (y of h) print(y);</lang>
/*
two
one
three
*/
 
for (y of h) print(y);
/*
2
1
3
*/</lang>
 
=={{header|jq}}==