for..of
ES6 added a for..of loop, a loop that produces a sequence of values in an iterator. The value o ffor..of loop must be one iterable.
var a = ["a", "b","c","d","e"]
for(var idx in a){
console.log(idx)
}
// 0 1 2 3 4
for(var val of a){
console.log(val)
}
// a b c d e
Code language: JavaScript (javascript)
for..in
Loop over the keys/indexes of the array a
and for..of
over the values of array a
.
ES6 previous code
var a = ["a", "b","c","d","e"]
for(var val, ret, it = a[Symbol.iterator]();(ret=it.next()) && !ret.done){
val = ret.value
console.log(val)
}
// a b c d e
Code language: JavaScript (javascript)
Under the hood, the for..of
loop asks the iterable for an iterator, and then repeatedly calls the iterator to assign the value it produces to the loop iteration variable.
JavaScript Standard built-in values that default to iterable include:
- Array
- Strings
- Generators
- Collections/TypedArrays
String iteration method
for(var c of "hello"){
console.log(c)
}
// h e l l o
Code language: JavaScript (javascript)
The raw string value is cast to the equivalent String wrapper object, which is a iterable
for(XYZ of ABC)
XYZThis position can be either an assignment expression or a declaration . Here is an example of an assignment expression:
var o = {}
for(o.a of [1,2,3]){
console.log(o.a)
}
o // {a:3}
for({x:o.a} of [{x:1},{x:2},{x:3}]){
console.log(o.a)
}
o // {a:3}
Code language: JavaScript (javascript)
With break, continue, return
the loop is terminated early.
Custom iterator
By understanding the underlying layer, for..of
ask iterable
for an iterator, and then call the iterator repeatedly to assign the value it produces to the loop iteration variable. Then I can customize one iterable.
var o = {
[Symbol.iterator](){
return this
},
next(){
if(!val){
val = 1
}else{
val ++
}
return {value:val, done:val== 6}
}
}
for(var val of o[Symbol.iterator]()){
console.log(val)
}
Code language: JavaScript (javascript)
It can be seen that the custom iterator satisfies two conditions, [Symbol.iterator]
attributes, and the returned object has a next
method, and the next
return value of the method must be in the form {value:xx,done:xx}
, if encountered done:true
, the loop ends.
Conclusion: The above is the whole content of the for..of loop, which can loop over iterable objects