Home > Blockchain >  How do i loop through an array backwards?
How do i loop through an array backwards?

Time:11-05

i am attempting to make snake in java script using p5.js and have the snake as an array where the head is the first index and the tail every spot after. i am trying to loop through the array backwards for moving the boxes so they don't all end up on one square but the rest of the code stopped working when i tried this. the head is supposed to go down and this works when i loop through normally with the head at the other end, but need to go backwards so i can add more into the array. here is my code:

function setup() {
  createCanvas(400, 400);
}

class SnakeBlock{
  constructor(x, y, isHead){
    this.x = x;
    this.y = y;
    this.isHead = isHead;
  }
  
  draw(){
    fill("green");
    noStroke();
    rect(this.x * 40, this.y * 40, 40, 40)
  }
  
  move(snake, x){
    if(this.isHead == true){
      this.y  = 1;
    }
    else{
      this.y = snake[x - 1].y;
      this.x = snake[x - 1].x;
    }
  }
}

var length = 4;

var moveCounter = 20;

var snake = [new SnakeBlock(0, 0, true),new SnakeBlock(1, 0, false),new SnakeBlock(2, 0, false), new SnakeBlock(3, 0, false)];

function draw() {
  background(0);
  for(let x = length - 1; x > 0; x--){
      snake[x].draw();
  }
  if(moveCounter == 0){
    for(let x = length - 1; x > 0; x--){
      snake[x].move(snake, x);
      snake[x].draw();
    }
    moveCounter = 20;
  }
  else{
    moveCounter -= 1;
  }
  
  
}

back when i had it looping the other way the snake head would move down as seen in the move() function in the snake class, but when i loop backwards it doesn't move down at all and just stays in place. yes i did reverse the array when looping the other way.

CodePudding user response:

Simple, loop the other way. Instead of i use i--:

for(i = 0; i < array.length; i  ){
    // do something with array[i]
}

// you go backwards:
for(i = array.length - 1; i >= 0; i--){
    // do something with array[i]
}

CodePudding user response:

Option 1

var arr = [1, 2, 3, 4, 5];
 
for (var i = arr.length - 1; i >= 0; i--) {
    console.log(arr[i]);
}

Option 2

var arr = [1, 2, 3, 4, 5];
 
arr.slice().reverse().forEach((item) => {
    console.log(item);
});

CodePudding user response:

You can achieve this using the Array.prototype.reduceRight() method

const arr = [1,2,3,4,5];
arr.reduceRight((_, el) => {
 console.log(el);
 // do stuff
 return el;
}, null)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

More about reduceRight - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight

  • Related