ES6 Iterator
Demo the use of Iterator in ES6
by Po-Jung Chen
JavaScript
/**
* Demonstrate an iterator
**/
let arr = [1, 2, 3]
console.log(typeof arr[Symbol.iterator]) // function
let current = arr[Symbol.iterator]()
console.log(current.next()) // Object {value: 1, done: false}
console.log(current.next()) // Object {value: 2, done: false}
console.log(current.next()) // Object {value: 3, done: false}
console.log(current.next()) // Object {value: undefined, done: true}
/**
* A function to simulate iterator
**/
var it = makeIterator(['a', 'b']);
console.log(it.next()) // { value: "a", done: false }
console.log(it.next()) // { value: "b", done: false }
console.log(it.next()) // { value: undefined, done: true }
function makeIterator(array) {
let nextIndex = 0;
return {
next: function() {
return nextIndex < array.length ? {
value: array[nextIndex++],
done: false
} : {
value: undefined,
done: true
};
}
};
}
/**
* Create a custom iterable array
**/
arr[Symbol.iterator] = function() {
let nextIndex = 0
return {
next() {
return nextIndex < arr.length ? {
value: arr[nextIndex++] * 2,
done: false
} : {
value: undefined,
done: true
};
}
}
}
for (let item of arr) {
// 當 done 為 true 時就不在疊代
console.log(item) // 2, 4, 6
}
/**
* Create a custom iterable Object
**/
let person = {
firstName: 'Aaron',
lastName: 'Chen',
hobbies: ['computer', 'programming', 'sports'],
// 讓 JS 知道這個物件具有 iterator,所以是 iterable
[Symbol.iterator]: function() {
let index = 0
let hobbies = this.hobbies
return {
next() {
return index < hobbies.length ? {
done: false,
value: hobbies[index++]
} : {
done: true,
value: undefined
}
}
}
}
}
for (let hobby of person) {
console.log(hobby) // computer, programming, spots
}