文章 评论 浏览 29
一秒后同时输出 1、4、9如果要每隔一秒输出把 forEach 换成普通 for 循环或者 for...of... 循环即可这里并行进行是因为 forEach 实现的问题,源码里用 while 来一次性执行了所有回调具体参考官网 polyfill: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
一秒后同时输出 1、4、9
如果要每隔一秒输出把 forEach 换成普通 for 循环或者 for...of... 循环即可
这里并行进行是因为 forEach 实现的问题,源码里用 while 来一次性执行了所有回调
具体参考官网 polyfill: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
你这个用 while 来一次性执行了所有回调描述不太准确吧,普通的for 等于同一个块作用域连续await,而forEach的回调是一个个单独的函数,跟其他回调同时执行,互不干扰
function test() { list.forEach(async x=> { const res = await square(x) console.log(res) }) //forEach循环等于三个匿名函数; (async (x) => { const res = await square(x) console.log(res) })(1); (async (x) => { const res = await square(x) console.log(res) })(2); (async (x) => { const res = await square(x) console.log(res) })(3); // 上面的任务是同时进行 } async function test() { for (let x of list) { const res = await square(x) console.log(res) } } //等价于 async function test() { const res = await square(1) console.log(res) const res2 = await square(2) console.log(res) const res3 = await square(3) console.log(res) }
对象转字符串的总结中:“所以总结下,对象转字符串(就是 Number() 函数)可以概括为...”,这里应该是 String() 函数吧
文章 0 评论 0
接受
你这个用 while 来一次性执行了所有回调描述不太准确吧,普通的for 等于同一个块作用域连续await,而forEach的回调是一个个单独的函数,跟其他回调同时执行,互不干扰
第 160 题:输出以下代码运行结果,为什么?如果希望每隔 1s 输出一个结果,应该如何改造?注意不可改动 square 方法