异步 JavaScript 使用 setTimeout 和重新创建 forEach 的挑战问题

Asynchronous JavaScript Challenge question with setTimeout and recreating forEach

请帮忙!我一直在尝试自己解决这个问题,但总是碰壁。

重新创建内置数组方法 forEach - 编写一个将数组 arr 和回调函数 cb 作为参数的函数。 forEach 函数将遍历 arr,将每个元素及其索引作为参数传递给 cb。 创建一个名为 delays 的变量,并为其分配一个数组,其中包含数字 200、500、0 和 350(按此顺序)。 编写一个函数 delayLog,它以 delayTime 和索引 i 作为输入。调用时,该函数应等待 delayTime 毫秒,然后再登录到控制台,"printing element i"("i" 替换为传入的实际索引)。 综上所述,运行 使用您创建的 forEach 函数对延迟数组的每一项执行 delayLog 函数。

这就是我目前所拥有的。不太确定在哪里应用 setTimeout。谢谢!!!

function forEach(array,cb){
  for(let i=0;i<array.length;i++){
    console.log("printing element",i)
  }
}

let delays=[200,500,0,350];

function delayLog(delayTime,cb){
setTimeout(forEach(delayTime),cb);
}

delayLog(delays,i=>i)

来自控制台:

printing element 0
app.js:330 printing element 1
app.js:330 printing element 2
app.js:330 printing element 3

这是你想要的:

function forEach(arr, cb){
  for(let i=0,l=arr.length; i<l; i++){
    setTimeout(()=>{
      cb(i);
    }, arr[i]);
  }
}
function delayLog(i){
  console.log('printing element '+i);
}
forEach([200, 500, 0, 350], delayLog);

function forEach(arr, cb){
  for(let i = 0; i < arr.length; i++){
    cb(arr[i], i);
  }
}

 delays = [200, 500, 0, 350];

function delayLog(delayTime, i){
  setTimeout(() => {
    console.log(`printing element ${i}`)
  }, delayTime);
}

forEach(delays, delayLog);