for...in、for...of、for await...of

简介: for...in、for...of、for await...of

处世应当谦虚,切忌轻人傲世。——佚名

简单说下区别:

for...in遍历出来的是key

var obj = {a:1, b:2, c:3};
for (var prop in obj) {
  console.log("obj." + prop + " = " + obj[prop]);
}
// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

for...of遍历出来的是元素

const array1 = ['a', 'b', 'c'];
for (const element of array1) {
  console.log(element);
}
// Expected output: "a"
// Expected output: "b"
// Expected output: "c"

for await...offor...of差不多,但支持遍历由Promise组成的可迭代对象(如数组),使用时会自动await直到Promise执行结束才执行

var asyncIterable = {
  [Symbol.asyncIterator]() {
    return {
      i: 0,
      next() {
        if (this.i < 3) {
          return Promise.resolve({ value: this.i++, done: false });
        }
        return Promise.resolve({ done: true });
      }
    };
  }
};
(async function() {
   for await (num of asyncIterable) {
     console.log(num);
   }
})();
// 0
// 1
// 2
相关文章
|
2天前
|
前端开发 JavaScript
Promise、async和await
Promise、async和await
16 0
|
2天前
|
前端开发 JavaScript
什么是 async、await ?
什么是 async、await ?
|
6月前
|
JSON 前端开发 JavaScript
async/await的应用
async/await的应用
31 0
|
8月前
|
前端开发 JavaScript
|
2天前
|
前端开发 JavaScript
async/await
async/await
17 0
|
18小时前
|
前端开发 JavaScript 开发者
阿珊带你深入理解 async/await 函数
阿珊带你深入理解 async/await 函数
|
2天前
|
JSON 前端开发 JavaScript
什么是async和await?
什么是async和await?
11 0
|
2天前
|
前端开发 JavaScript