迭代一个数组,一旦到达终点就返回

问题描述 投票:0回答:2

What I want

我试图从一开始就迭代一个数组(记录所有元素),然后一旦到达结束,返回数组。一旦它再次到达开始,它将再次通过阵列。它会永远这样做。

例:

数组= [1,2,3,4,5]

记录:1,2,3,4,5,4,3,2,1,2,3 ......


What I have tried

这是我尝试过的:

let a = 0;
let dir = -1;
let arr = new Array();

function setup() {
  for (let i = 0; i < 10; i++) {
    arr.push(i);
  }
}

function draw() {
  for (let el of arr) {
    console.log(el);
  }

  if (i >= arr.length || i <= 0) {
    dir *= -1;
  }

  i += dir;
}

如果您不知道,这是一个p5.js草图。 setup()函数在页面加载上运行,draw()函数重复运行。


What happened

This is what happened

javascript arrays iteration
2个回答
0
投票

stop_count仅用于测试,防止它永远循环。

let arr = [1,2,3,4,5];
let dir = 1;
let stop_count = 0;

while (stop_count <10) {
    let i;
    i = dir===1 ? 0 : arr.length-1;
    console.log(arr[i]);
    i+=dir;
    while (i < arr.length-1 && i >=1){
        console.log(arr[i]);
        i+=dir;
    }
    dir = dir*-1;
    stop_count += 1;
}

0
投票

你可以使用数组函数,如concatmapslicereverseforEachmap而不是循环:

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

var upDown = arr.concat(
  //not the last one or 5 will be logged twice
  arr.slice(0,-1)
  //reverse order
  .reverse()
);
upDown.forEach(
  item=>console.log(item)
);

您的绘图功能可能如下所示:

var draw =(function(){
  var arr = [1,2,3,4,5];
  var upDown = arr.concat(
    arr.slice(0,-1)
    .reverse()
  );
  var index = -1;
  return function(){
    index = (index===upDown.length-1)
      ? 0
      : index+1;
    console.log(upDown[index]);
  }
}());//IIFE to set up upDown array and index
© www.soinside.com 2019 - 2024. All rights reserved.