Iterating over each element in a ForEach loop to increment its value

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?

Answer №1

Give this a try

function MoveSnakeLeft(){
  SnakePieces.forEach((Piece, i)=> {
    Piece.style.gridRowStart = (StartingPosY + y);
    Piece.style.gridColumnStart = (StartingPosX + x) + i;
  });
};

LATEST UPDATE To start the count from 1 instead, use this revised code snippet:

function MoveSnakeLeft(){
  SnakePieces.forEach((Piece, i)=> {
    Piece.style.gridRowStart = (StartingPosY + y);
    Piece.style.gridColumnStart = (StartingPosX + x) + (i + 1);
  });
};

In the forEach loop, you can include an index parameter like this:

forEach(item, index) => { ... }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble connecting JavaScript to Node application for proper functionality

After setting up Node/Express/EJS, I am now trying to include js files, but my alert("working"); is not working as expected. Quite ironic, isn't it? The main objective is to load learnJs.js in the browser and trigger the alert so that I can confirm e ...

Is there a more efficient method for performing multiple JavaScript replace calls rather than executing them individually?

In my Javascript code, I am creating a string that includes HTML content. Currently, my approach involves the following steps: var filter = ""; filter = util.getTemplate( "tmp_filter", temps ); filter = filter.replace( 'id="tmp_filter"','& ...

Creating categories in AngularJS using an array

<table class="table-striped table-bordered table-condensed"> <tbody> <tr ng-if="$index%3==0" ng-repeat="permission in vm.parent.getAllPermissions()"> <td ng-repeat="i in [0,1,2]" class="col-xs-2"> ...

Is it possible to decode a two-dimensional array of objects in JSON?

My scenario involves a two-dimensional array of objects structured as follows: function test(n){ this.id = n; } var testArray= new Array(2); for(i = 0; i < testArray.length; i++){ testArray[i] = new Array(2); for(j = 0; j < testArray[i].lengt ...

Breaking apart images with HTML5 canvas

I am currently working on creating a sliding puzzle piece game. By utilizing the canvas element, I successfully divided the image into multiple pieces. To shuffle these pieces, I stored their coordinates in an array, randomized the coordinates, and then up ...

Animating SVG while scrolling on a one-page website

Is there a way to incorporate SVG animation scrolling in a single page website? I am inspired by websites like and . The first one stands out to me because the animation is controlled by scrollup and scrolldown actions. I haven't written any of my S ...

What is a reliable method for automatically refreshing a webpage despite encountering server errors?

I'm working on an HTML+JS web page that refreshes itself automatically every few seconds using http-equiv="refresh". The problem is, sometimes the server returns a 502 "bad gateway" error, preventing the HTML code from loading and causing th ...

Implementing dynamic attribute id addition to select option

Here's the code snippet I'm currently working with: Included HTML <select id="drop_opts"> <option>1<option> <option>2<option> <option>3<option> </select> ...

Working on executing various methods with a JavaScript client on a Flask RESTful API that requires authentication

I'm currently developing a JavaScript client-side app to interact with a Flask RESTful API. I've implemented some methods that require user authentication, but for some reason, even after logging into the server, I receive a 401 error (Unauthoriz ...

Creating a Union Type from a JavaScript Map in Typescript

I am struggling to create a union type based on the keys of a Map. Below is a simple example illustrating what I am attempting to achieve: const myMap = new Map ([ ['one', <IconOne/>], ['two', <IconTwo/>], ['three ...

How to utilize AngularJS to submit a Symfony2 form

I'm currently working on developing an application with Symfony2 for the backend and considering using AngularJS for the frontend. My plan is to integrate Symfony forms into the project as well. I have successfully set up the form with all the necessa ...

I'm having trouble with my react-big-calendar not updating when I switch between day, month, or week views -

Why won't my calendar change to the week view when I click on that section? https://i.stack.imgur.com/gh2aO.png In the screenshot above, my default view is set to month, but when I attempt to switch to week, it only highlights the option without cha ...

Pressing enter to submit a form when the submit button is not visible is functional in Firefox, but has no effect in Chrome

There is a form with various input fields and a hidden submit button (hidden using style="display:none"). Interestingly, in Firefox, pressing the return key while an input field is focused automatically submits the form. However, in Chrome, hitting retur ...

Dynamically enhance the JSON root with additional value

Oh dear, I'm feeling quite perplexed right now. I created a JSON element in the following way: var planet = {"continent": []}; planet.continent.push({name: "Asia", flag: "yes", countries: []}); planet.continent[0].countries.push({name: "Japan", capi ...

Change the background color of numbers in an array using DOM manipulation in JavaScript

Can someone assist me with the following task: 1. Generate an array containing 10 numbers ranging from 0 to 360. 2. Display these numbers on the DOM within a chosen element. 3. Adjust the background color of each number based on its HUE value in (hue, sat ...

Updating materials within the Forge

Currently, we have implemented a system where the client retrieves object states when the page loads, changing the colors of 'pending' objects in the model. We continue to poll for changes to update the coloring - initially coloring pending objec ...

Running the command Yarn build with Vite.js and React.js is encountering issues and is not functioning properly

Lately, I've been experimenting with Vite in my React projects. However, when I execute the command yarn build, it creates a Build folder but the application fails to work. When I open the index.html file, all I see is a blank page. Interestingly, e ...

What steps should I take to make sure my asp.net validators execute prior to invoking client-side javascript functions?

I am facing an issue with my asp.net application which has basic CRUD functionality. I have set up several asp.net validators on a customer details capture page to ensure required fields are filled out. Additionally, I have added a JS confirm box to the sa ...

The customer opts to store all images indefinitely into the data stream

I have set up a node server that captures images from a webcam at regular intervals and sends them to the client using the Delivery.js node module. Upon monitoring the browser resources in Chrome development tools, it appears that each image sent is being ...

If there are results from the second table in PHP, then use LEFT JOIN to add them to an array

In my dictionary project, I am attempting to enhance its capabilities by displaying definitions for certain terms if they are available. The data is extracted from two tables in the following manner: $query = $db->query("SELECT * FROM ".DICTIONARY ...