So new ECMAScript 6 has introduced for .. of
loop syntax.
Unfortunately, there aren't many documentations out there that explains what this really does. As in how it differs from using Array.prototype.forEach
or for .. in
loop.
Is it just another imperative way to perform Array.prototype.forEach
?
I've already read Mozilla's doc here. But still the idea is too vague to me.
Anyone cares to explain to this halfwit?
Quick hint
for..of
takes the element.
var a = ['a','b','c'];
for (let elem of a){
console.log(elem);
}
// output:
// 'a'
// 'b'
// 'c'
for..in
takes the index.
var a = ['a','b','c'];
for (let i in a){
console.log(i);
}
// output:
// 0
// 1
// 2
.forEach
takes element and index (optional).
var a = ['a','b','c'];
a.forEach(function(elem,i){
console.log(i + ': ' + elem);
});
// output:
// 0: 'a'
// 1: 'b'
// 2: 'c'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With