Seeking assistance with arrays and increments.
I've created a function that applies the same style to each new element in an array:
function SnakeBodyLeft(){
StorePositions.forEach(BodySnake => {
BodySnake.style.gridRowStart = (Initial_y + y);
BodySnake.style.gridColumnStart = (Initial_x + x) + 1;
});
};
// The current result is:
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 forth...
I aim to create a function that achieves the above, but increments the value by +1 for each subsequent element while maintaining the initial value for the first elements. The desired outcome would be as follows:
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 attempted to create a variable 'i' and increment it by 1, but found that when I did this, the increment of 'i' applied to all elements in the array rather than just the new ones.
let i = 1++;
function SnakeBodyLeft(){
StorePositions.forEach(BodySnake => {
BodySnake.style.gridRowStart = (Initial_y + y);
BodySnake.style.gridColumnStart = (Initial_x + x) + i ;
});
};
// This resulted 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
Essentially, as the index increases (0, 1, 2, 3...), the value 'i' should also grow in each new element at that index (0, 1, 2, 3...).
However, I'm currently stuck! Can anyone provide guidance?