【问题标题】:Do something within a JavaScript array for loop在 JavaScript 数组 for 循环中执行某些操作
【发布时间】:2019-02-20 18:37:46
【问题描述】:

我正在尝试找出一种方法来循环遍历数组,使用该 array[index] 暂停函数执行 x 秒并移动到该数组中的下一个索引。

这就是我目前所取得的成就。它打印出整个数组,但我需要它只打印出一个值,用它做一些事情,然后继续下一个,依此类推。

var destinations = ['Greece', 'Maldives', 'Croatia', 'Spain'];

var index = 0;

for (index = 0; index < destinations.length; index++){
  console.log(destinations[index]);
};

【问题讨论】:

  • 那么...你卡在哪里了?你想做什么?你遇到了什么问题?
  • @tymeJV 我需要遍历这个数组,一次抓取 1 个值,使用它,然后抓取下一个,依此类推。最重要的是,每次获取一个值时我都需要暂停这个函数,所以它不是一次吐出所有结果,而是一个接一个地吐出
  • 看看 forEach 函数,mdn var destinations = ['Greece', 'Maldives', 'Croatia', 'Spain']; destinations.forEach(function(element, i) { // 对每个值做一些事情 console.log(element, i); });

标签: javascript arrays loops for-loop


【解决方案1】:

您可以在Array#[@@iterator]() 中使用Symbol.iterator 的实现来获取iteration protocols 并迭代直到没有更多元素可用。

var destinations = ['Greece', 'Maldives', 'Croatia', 'Spain'],
    gen = destinations[Symbol.iterator]();
    interval = setInterval(function () {
        var g = gen.next();
        if (g.done) {
            clearInterval(interval);
            return;
        }
        console.log(g.value);
    }, 1000);

【讨论】:

    【解决方案2】:

    您可以使用setTimeout 来执行此操作。

    var time_between_steps = 1000
    var destinations = ['Greece', 'Maldives', 'Croatia', 'Spain']
    var index = 0
    
    function nextItem(){
      // do things here with destinations[index]
      console.log(destinations[index])
      
      index++
      
      // if we have not yet reached the end of the array, run nextItem again after time_between_steps
      if(index<=destinations.length-1)
        setTimeout(nextItem,time_between_steps)
    }
    
    
    nextItem()

    【讨论】:

      【解决方案3】:

      setTimeout可以在这里使用:

      基本上,您可以定义一个方法processItem 并使用当前参数调用它。延迟也可以用变量来设置。

      延迟之后,该方法被调用一个参数。

      var delay = 1000; // 1 sec
      var destinations = ['Greece', 'Maldives', 'Croatia', 'Spain'];
      var index = 0;
      
      function processItem(item){
        console.log("Item " + item);
        // do stuff
      }
      
      function iterate(index){
        processItem(destinations[index]);
        index++;
        if (index < destinations.length){
         setTimeout(iterate, delay, index);
        }
      }
      
      iterate(index);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-20
        • 1970-01-01
        • 2023-02-10
        • 2021-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多