JavaScript

超轻量级php框架startmvc

ES6入门教程之Iterator与for...of循环详解

更新时间:2020-05-12 09:42:01 作者:startmvc
本文主要介绍了关于ES6中Iterator与for...of循环的相关内容,分享出来供大家参考学习,需要

本文主要介绍了关于ES6中Iterator与for...of循环的相关内容,分享出来供大家参考学习,需要的朋友们下面来一起看看详细的介绍:

一、Iterator(遍历器)

遍历器(Iterator)是一种协议,任何对象只要部署了这个协议,就可以完成遍历操作。在ES6中遍历操作特质for….of循环。

它的作用主要有两个:

  • 为遍历对象的属性提供统一的接口。
  • 使对象的属性能够按次序排列。

ES6的遍历器协议规定,部署了next方法的对象,就具备了遍历器功能。next方法必须返回一个包含value和done两个属性的对象。value属性是当前遍历的位置的值,而done属性是一个布尔值,用来表示遍历是否结束。


 function makeIterator(array) {
 var nextIndex = 0;

 return {
 next: function() {
 return nextIndex < array.length ?
 {value: array[nextIndex++], done: false} :
 {value: undefined, done: true};
 }
 }
 }

 var it = makeIterator(['a', 'b']);
 it.next().value; //'a'
 it.next().value; //'b'
 it.next().done; // true

在上面代码片段中,定义了一个makeIterator函数,它的作用是返回一个遍历器对象,用来遍历参数数组。特别需要注意的是next返回值的构造。

下面,再看看一个遍历器的示例代码片段:


 function idMaker() {
 var index = 0;
 return {
 next: function() {
 return {value: index++, done: false};
 }
 }
 }

 var it = idMaker();
 it.next().value; //'0'
 it.next().value; //'1'
 it.next().value; //'2'

二、for…of 循环

在ES6中,一个对象只要部署了next方法,就被视为是具有了iterator接口,就可以用for…of循环遍历它的值。


 function idMaker() {
 var index = 0;
 return {
 next: function() {
 return {value: index++, done: false};
 }
 }
 }

 for (var n of it) {
 if (n > 5) {
 break;
 console.log( n );
 }
 }
 //0
 //1
 //2
 //3
 //4
 //5

上面的代码说明,for….of默认从0开始循环。

数组原生具备iterator接口


 const arr = [1, 5, 3, 9];
 for (let v of arr) {
 console.log( v );
 }
 //1
 //5
 //3
 //9

相比较,Js原有的for…in循环,只能获得对象的键名,不能直接获取键值。ES6提供了for…of循环,允许遍历获取键值。


 var arr = ['a', 'b', 'c', 'd'];

 for (a in arr) {
 console.log( a );
 }
 //0
 //1
 //2
 //3

 for (a of arr) {
 console.log( a );
 }
 //0
 //1
 //2
 //3

上面的代码片段表明,for…in循环读取键名,而for…of循环读取键值。

对于Set和Map结构的数据,可以直接使用for…of循环。


 var name = ['S', 'D', 'J', 'Z', 'G', 'G', 'G'];
 for ( var e of name) {
 console.log( e );
 }
 //S
 //D
 //J
 //Z
 //G


 var es6 = new Map();
 es6.set('edition', 6);
 es6.set('committee', 'TC39');
 es6.set('standard', 'ECMA-262');
 for(var [name, value] of es6) {
 console.log(name + ": " + value);
 }
 // edition: 6
 // commttee: TC39
 // standard: ECMA-262

在上面的代码片段中,演示了如何遍历Set结构和Map结构,后者是同是遍历键名和键值。

对于普通的对象,for...of结构不能直接使用,否则则会报错。必须项部署iterator接口才能使用。但是,在这种情况下,for...in循环依然可以遍历键名。


 var es6 = {
 name: "G.Dragon",
 year: 22,
 love: "coding"
 };

 for (e in es6) {
 console.log( e );
 }
 //name
 //year
 //love

 for( e of es6) {
 console.log( e );
 }
 // TypeError: es6 is not iterable

最后,总结一下。for...of循环可以使用的范围包括数组、类似数组的而对象(比如argument对象、DOM NodeList对象)、Set和Map结构、后文的Generator对象,以及字符串。下面是使用for...of循环遍历字符串和DOM NodeList对象的例子。


 // 字符串例子
 let str = "hello";

 for (let s of str) {
 console.log( s );
 }
 //h
 //e
 //l
 //l
 //o

 // DOM NodeList对象的例子
 let paras = document.getSelectorAll("p");
 for (let p of paras) {
 p.classList.add("test");
 }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

es6 for of es6 for of 遍历对象 es6 iterator