Сделайте что-нибудь в массиве JavaScript для цикла - PullRequest
0 голосов
/ 20 февраля 2019

Я пытаюсь выяснить, как выполнить цикл по массиву, что-то сделать с этой функцией паузы [index] массива в течение x секунд и перейти к следующему индексу в этом массиве.

Вот чтоЯ добился до сих пор.Он распечатывает весь массив, но мне нужно, чтобы он распечатывал только одно значение, что-то с ним делал, затем переходил к следующему и т. Д.

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

var index = 0;

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

Ответы [ 3 ]

0 голосов
/ 20 февраля 2019

Вы можете взять итерационные протоколы с реализацией Symbol.iterator в Array#[@@iterator]() и выполнять итерацию до тех пор, пока больше не будет доступных элементов.

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);
0 голосов
/ 20 февраля 2019

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);
0 голосов
/ 20 февраля 2019

Вы можете использовать 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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...