阿超
>
for...in、for...of、for await...of
处世应当谦虚,切忌轻人傲世。——佚名
简单说下区别:
for...in
遍历出来的是key
1 2 3 4 5 6 7 8 9 10
| var obj = {a:1, b:2, c:3};
for (var prop in obj) { console.log("obj." + prop + " = " + obj[prop]); }
|
for...of
遍历出来的是元素
1 2 3 4 5 6 7 8 9
| const array1 = ['a', 'b', 'c'];
for (const element of array1) { console.log(element); }
|
for await...of
和for...of
差不多,但支持遍历由Promise
组成的可迭代对象(如数组),使用时会自动await
直到Promise
执行结束才执行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| 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); } })();
|