Search code examples
javascriptarraysforeachincrement

Incrementing value with a ForEach loop to apply on each element


looking for help with arrays and increments.

I have a function which applies the same style to each new element in an array as you can see below.

function SnakeBodyLeft(){
  StorePositions.forEach(BodySnake => {
    BodySnake.style.gridRowStart = (Initial_y + y);
    BodySnake.style.gridColumnStart = (Initial_x + x)+1 ;
  });
};

// this results in

StorePositions[0] = BodySnake.style.gridColumnStart = (Initial_x + x)+1 
StorePositions[1] = BodySnake.style.gridColumnStart = (Initial_x + x)+1
StorePositions[2] = BodySnake.style.gridColumnStart = (Initial_x + x)+1

And so on...

I want to write a function that does what is shown above , but increments the value +1 for Each new element and keep the initial value for the first elements. The result would be somethink like :

StorePositions[0] = BodySnake.style.gridColumnStart = (Initial_x + x)+1 
StorePositions[1] = BodySnake.style.gridColumnStart = (Initial_x + x)+2
StorePositions[2] = BodySnake.style.gridColumnStart = (Initial_x + x)+3
StorePositions[3] = BodySnake.style.gridColumnStart = (Initial_x + x)+4

And so on....   

I have tried to make 1 a variable called i and increment it. But when I do this , the increment of i is applied to all elements in the array and not just the new elements.

let i = 1++;

function SnakeBodyLeft(){
  StorePositions.forEach(BodySnake=> {
    BodySnake.style.gridRowStart = (Initial_y + y);
    BodySnake.style.gridColumnStart = (Initial_x + x) + i ;
  });
};


//this results in the incremented value being applied to all elements , not just the new ones .

StorePositions[0] = BodySnake.style.gridColumnStart = (Initial_x + x)+1 
StorePositions[1] = BodySnake.style.gridColumnStart = (Initial_x + x)+1
StorePositions[2] = BodySnake.style.gridColumnStart = (Initial_x + x)+1

or

StorePositions[0] = BodySnake.style.gridColumnStart = (Initial_x + x)+2 
StorePositions[1] = BodySnake.style.gridColumnStart = (Initial_x + x)+2
StorePositions[2] = BodySnake.style.gridColumnStart = (Initial_x + x)+2


Basically , as the index grows(0,1,2,3...) , so should the value i in each new element in the index.(0,1,2,3...).

But Iam kinda stuck ! Anyone can help ?


Solution

  • Try this

    function SnakeBodyLeft(){
      StorePositions.forEach((BodySnake, i)=> {
        BodySnake.style.gridRowStart = (Initial_y + y);
        BodySnake.style.gridColumnStart = (Initial_x + x) + i;
      });
    };
    

    UPDATE If you need to start the increment from 1 then do this instead:

    function SnakeBodyLeft(){
      StorePositions.forEach((BodySnake, i)=> {
        BodySnake.style.gridRowStart = (Initial_y + y);
        BodySnake.style.gridColumnStart = (Initial_x + x) + (i + 1);
      });
    };
    

    You can add an index for the forEach like so forEach(element, index) => { ... }