解决方案
for / forEach / for..of
// for for (var b; b = a.pop(); ) { // for 循环的特殊用法 do_sth(b); } // forEach [].forEach(function (item, index) { console.log(index + " " + item) }); [].forEach(function (item, index) { it => console.log(it) }); [].forEach(element => { // do some stuff }); // for...of => does use an object-specific iterator and loops over the values generated by that. const array1 = ['a', 'b', 'c']; for (const element of array1) { console.log(element); } // for...in => loops over enumerable property names of an object. const object = { a: 1, b: 2, c: 3 }; for (const property in object) { console.log(`${property}: ${object[property]}`); }
async…await
async function – JavaScript | MDN
javascript – Using async/await with a forEach loop – Stack Overflow
通过 async 定义的函数,允许异步执行,而对该函数的调用使用 await 能够等待该异步函数执行结束。
function resolveAfter2Seconds() { return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 2000); }); } async function asyncCall() { console.log('calling'); const result = await resolveAfter2Seconds(); console.log(result); // expected output: "resolved" } asyncCall();
注意事项,在 forEach 中传入 async 标注的函数是无效的,因为 forEach 会并行执行函数。
参考文献
declaration for variable in while condition in javascript – Stack Overflow
JavaScript Array forEach() Method
for…in – JavaScript | MDN
for…in – JavaScript | MDN
javascript – What is the difference between ( for… in ) and ( for… of ) statements? – Stack Overflow