JavaScript   发布时间:2022-04-16  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ES6入门教程之Iterator与for...of循环详解大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

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

一、Iterator(遍历器)

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

它的作用主要有两个:

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

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

{ 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返回值的构造。

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

{ 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循环遍历它的值。

{ 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接口

{ console.log( v ); } //1 //5 //3 //9

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

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循环。

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循环依然可以遍历键名。

{ 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对象的例子。

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入门教程之Iterator与for...of循环详解全部内容,希望文章能够帮你解决ES6入门教程之Iterator与for...of循环详解所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。