使用

var arr = [1,2,3,4];
for (let i of arr) {
	console.log(i); // 获取值
}
for (let i in arr) {
	console.log(i); // 获取下标
}

Untitled

在对象上部署 iterator,使其可以使用 for...of

const obj = {
	start: [8,6,1,2,3,4],
  end: [5,6,7,2,3],
	[Symbol.iterator]() {
    let index = 0,
        arr = [...this.start, ...this.end],
        len = arr.length;
  	return {
    	next() {
      	return index < len ?
          { value: arr[index++], done: false } :
          { value: undefined, done: true }
      }
    }
  }
}
for(let i of obj){
	console.log(i);
}

const arr1 = [...obj]; // 部署了迭代器接口的对象可以使用...运算符
console.log(arr1);

Untitled

🌈 for await of

我们来看以下场景哈

function fn (time) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`${time}毫秒后我成功啦!!!`)
    }, time)
  })
}

fn(3000).then(res => console.log(res))
fn(1000).then(res => console.log(res))
fn(2000).then(res => console.log(res))

结果是

1000毫秒后我成功啦!!!
2000毫秒后我成功啦!!!
3000毫秒后我成功啦!!!

但是我想要这个结果

3000毫秒后我成功啦!!!
1000毫秒后我成功啦!!!
2000毫秒后我成功啦!!!

第一时间我们肯定想到的是 async/await

function fn (time) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`${time}毫秒后我成功啦!!!`)
    }, time)
  })
}

async function asyncFn () {
  // 排队
  const data1 = await fn(3000)
  console.log(data1) // 3秒后 3000毫秒后我成功啦!!!
  const data2 = await fn(1000)
  console.log(data2) // 再过1秒 1000毫秒后我成功啦!!!
  const data3 = await fn(2000)
  console.log(data3) // 再过2秒 2000毫秒后我成功啦!!!
}

但是上面代码也是有缺点的,如果有几十个,那不是得写几十个await,有没有一种方法可以通过循环来输出呢?

function fn (time) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`${time}毫秒后我成功啦!!!`)
    }, time)
  })
}

async function asyncFn () {
  const arr = [fn(3000), fn(1000), fn(1000), fn(2000), fn(500)]
  for await (let x of arr) {
    console.log(x)
  }
}

asyncFn()
3000毫秒后我成功啦!!!
1000毫秒后我成功啦!!!
1000毫秒后我成功啦!!!
2000毫秒后我成功啦!!!
500毫秒后我成功啦!!!