Home >Web Front-end >JS Tutorial >Code example explanation of Iterator interface in ES6
The content of this article is to explain the code examples of the Iterator interface in ES6. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
In es6, when operating certain data structures (array object map set), how to use a unified method to operate? The Iterator interface implements such a function
1 .Application of Iterator in array
{ let arr = ['hello', 'world']; // 数组内部实现了iterator接口,所以直接调用[Symbol.iterator]() let map = arr[Symbol.iterator](); console.log(map.next()); // {value: "hello", done: false} console.log(map.next()); // {value: "world", done: false} console.log(map.next()); // {value: undefined, done: true} // value 表示数组元素,done表示循环是否有下一步状态,true:没有下一步了,false:循环没有结束 }
2. Customized Iterator interface
{ // object没有内置iterator接口,自定义iterator接口,让obj也可以使用for...of let obj = { start: [1,2,3], end: [4,5,6], // 声明iterator接口方法 [Symbol.iterator]() { // 先遍历start,再遍历end let arr = this.start.concat(this.end); let index = 0; // 返回next() return { next() { if (index <p><strong>3.for...of loop</strong> </p><pre class="brush:php;toolbar:false">{ // 数组内部实现了iterator接口,所以可以直接使用for...of循环 let arr = ['hello', 'world']; for (let value of arr) { console.log(value); // hello world } }
Front end
es6
14 times reading It takes 6 minutes to read
In es6, when operating certain data structures (array object map set), how to operate in a unified method? The Iterator interface implements such a function1. Application of Iterator in arrays{
let arr = ['hello', 'world'];
// 数组内部实现了iterator接口,所以直接调用[Symbol.iterator]()
let map = arr[Symbol.iterator]();
console.log(map.next()); // {value: "hello", done: false}
console.log(map.next()); // {value: "world", done: false}
console.log(map.next()); // {value: undefined, done: true}
// value 表示数组元素,done表示循环是否有下一步状态,true:没有下一步了,false:循环没有结束
}
2. Customized Iterator interface
{ // object没有内置iterator接口,自定义iterator接口,让obj也可以使用for...of let obj = { start: [1,2,3], end: [4,5,6], // 声明iterator接口方法 [Symbol.iterator]() { // 先遍历start,再遍历end let arr = this.start.concat(this.end); let index = 0; // 返回next() return { next() { if (index <p class="article fmt article__content"><br>3.for.. .of loop</p><p></p><pre class="brush:php;toolbar:false">{ // 数组内部实现了iterator接口,所以可以直接使用for...of循环 let arr = ['hello', 'world']; for (let value of arr) { console.log(value); // hello world } }
Sort by time
Show more comments
The above is the detailed content of Code example explanation of Iterator interface in ES6. For more information, please follow other related articles on the PHP Chinese website!