首页 > 语言 > JavaScript > 正文

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

2024-05-06 15:17:07
字体:
来源:转载
供稿:网友

本文主要介绍了关于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            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选