ES6 for…of..迭代

  • A+
所属分类:ES6

for...of语句在可迭代对象(包括 Array, Map, Set, String, TypedArray,arguments 对象等等)上创建一个迭代循环,对每个不同属性的属性值,调用一个自定义的有执行语句的迭代挂钩

语法:


for (variable of object) {
  statement
}
//variable 每一次迭代,不同属性的属性值会被赋值给该变量.
//object 一个可迭代对象.

例子:

遍历数组


const arr = [3,4,5,6]
for( let key of arr){
	console.log( key )
}
//will output 3,4,5,6

遍历DOM集合


let colDiv = document.querySelectorAll("div");

for (let oDiv of colDiv ) {
  oDiv.classList.add("test");
}

遍历生成器


const gen = function *(){
	yield 'l';
	yield 'x';
	yield 'y';
}

for( let str of gen() ){
	console.log( str )
}
//will output 'l' 'x' 'y'

for..of..只能遍历可迭代对象 如果要支持普通对象需要设置[Symbol.iteraror]属性


//for..of..实现的fibonacci
//for..of..只能迭代含有[Symbol.iterator]属性的对象
const obj = { 
	[Symbol.iterator](){ 
		let [a, b] = [0, 1];
		return {
			next: function(){
				[a, b] = [b, a+b];
				return {
					done: false,
					value: b
				}
			}
		} 
	} 
}
let i = 0;
for( let key of obj ){
	if( ++i > 20 ) return;
	console.log( key )
}

使用iterator迭代


const someArr = [1,2,3,4]
const someArrEntries = someArr.entries()
console.log( someArrEntries === someArrEntries[Symbol.iterator]() )//will output true

const arr = [1,2,3,4,5]

const ergodicObj = ( arr ) => {  
	const iter = arr.entries();
	let _n = null;
	let val = null;
	while( !(_n = iter.next()).done ){
		val = _n.value;
		console.log( `index-${val[0]}  value-${val[1]}` )
	}
}
weinxin
我的微信
欢迎来撩!!

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: