簡體   English   中英

observable - 如何使用 forEach 和 setTimeout 返回值? (與 Rxjs 無關)

[英]observable - how do I return values using forEach and setTimeout? (nothing to do with Rxjs)

我是 observablehq 筆記本的新手。 我發現這對我制作視覺效果原型非常有用。

我的問題是如何使用 javascript 的 setTimeout 迭代數組並返回值?

我的方法如下。

  1. 數組被聲明

    arr = [1,2,3,4,5]

  2. 迭代數組並返回值

     arr.forEach((d,i)=>{ setTimeout(()=>{ return d },i*1000)})

我如何實現這一目標?

我看到使用 Rxjs 的類似帖子,但我不使用它。 是否有實現這一目標的基本/基本方法?

我認為這不起作用的原因與關閉有關。 但想不出解決問題。

你可以使用這個:

你當然要等,這需要一段時間

{
  //Now, iterate over the array with setTimeout
  let myArr = [1, 2, 3, 4, 5];

  let newMap = [];

  for (let [index, d] of myArr.entries()) {
    const abc = await new Promise((resolve) => {
      setTimeout(() => {
        resolve(d);
      }, 1000 * index);
    });
    newMap.push(abc);
  }

  return newMap;
}

在此處輸入圖像描述

您可以嘗試以下解決方案

    myArr = [1, 2, 3, 4, 5];

//Now, iterate over the array with setTimeout
myArr.forEach(function(d, i) {
    setTimeout(function() {
        console.log(d);
        return d;
    }, 1000 * i);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM