Anonymous user
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(
console.log(x);
});</lang>▼
▲);</lang>
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(
return x.toUpperCase(x);
▲).join('\n'));</lang>
or, more flexibly, and with greater generality, obtain an accumulating fold from '''Array.reduce()'''
<lang
}, ""));</lang>▼
▲ "alpha beta gamma delta".split(' ').reduce(
▲ return lst.length - i + '. ' + x + '\n' + a;
▲)</lang>
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>▼
▲for each (y in h) print(y);
{{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>▼
▲for (y of h) print(y);
=={{header|jq}}==
|