繁体   English   中英

遍历数组并在到达末尾时返回

[英]Iterate through an array and back once it reaches the end

我想要的是

我试图从头开始遍历数组(记录所有元素),然后到达终点,再遍历数组。 一旦再次到达起点,它将再次通过阵列。 它将永远做到这一点。

例:

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

日志:1、2、3、4、5、4、3、2、1、2、3 ...


我尝试过的

这是我尝试过的:

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()函数则重复运行。


发生了什么

这是发生了什么

您可以使用诸如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

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM