JavaScript: for-of Loop
New in JS2015.
for (variable of iterable) {body}
The for-of loop is a syntax that lets you go thru Iterable Object 's values.
Iterate Over Array
for-of loop on Array Object
for (let x of [3, 4, 5]) { console.log(x); } /* [ prints 3 4 5 ] */
Iterate over array with index and value
Iterate over array with index and value. By Destructuring Assignment and Array.prototype.entries.
let xx = ["a", "b", "c"]; /* [ loop over array with index and value ] */ for (let [i, v] of xx.entries()) { console.log(i, v); } /* [ prints 0 a 1 b 2 c ] */
Iterate Over Characters in String
When used on string, it goes thru each char, not String Code Unit . This fixed a long time JavaScript problem.
/* [ for-of loop thru string. In each iteration, the value is a unicode char, not 16 bits byte sequence ] */ for (let x of "abπd") { console.log(x); } /* [ prints a b π d ] */
Iterate Over Members in a Set Object
/* [ for-of loop over set object ] */ let xx = new Set([3, 4, 5]); for (let v of xx) { console.log(v); } /* [ prints 3 4 5 ] */