Execute identical task using a for loop in JavaScript

Here is a sample code snippet:

var seats = []


    for (a = 0; a <= seatsNumFront; a++) {
        seats.push(new Seat((a * xPad) + 300, 60, 30, 30, id++, "A", a, "#998515"))
    }
    for (b = 0; b <= seatsNumFront; b++) {
        seats.push(new Seat((b * xPad) + 300, 100, 30, 30, id++, "B", b, "#998515"))
    }
    for (c = 0; c <= seatsNumFront; c++) {
        seats.push(new Seat((c * xPad) + 300, 140, 30, 30, id++, "C", c, "#998515"))
    }

I am looking to make these lines of code execute based on the value I specify.

For example: I want to set a variable and run the code only once according to that variable

So if we write:

var seats = []
var num = 3

for (c = 0; c <= seatsNumFront; c++) {
    seats.push(new Seat((c * xPad) + 300, 140, 30, 30, id++, "C", c, "#998515"))
}

Desired output:

var seats = []
var num = 3

for (a = 0; a <= seatsNumFront; a++) {
    seats.push(new Seat((a * xPad) + 300, 60, 30, 30, id++, "A", a, "#998515"))
}
for (b = 0; b <= seatsNumFront; b++) {
    seats.push(new Seat((b * xPad) + 300, 100, 30, 30, id++, "B", b, "#998515"))
}
for (c = 0; c <= seatsNumFront; c++) {
    seats.push(new Seat((c * xPad) + 300, 140, 30, 30, id++, "C", c, "#998515"))
}

Answer №1

It seems like you're looking to create a function, but I may not fully understand your exact requirements. Here's an example code snippet showcasing how you can encapsulate your for loop within a function that takes two parameters.

Update: After reviewing your additional explanation, I've included more code below.

//Variables specific to your implementation
var id = 0;  
var seatsNumFront = 1;
var seats = Array();
var xPad = 5

//Function to dynamically add seats based on 'value' (e.g., 60, 100, 140) and a character 'ch' (e.g., 'A', 'B', 'C')
function addSeats(value, ch){
    for(var i = 0;i <= seatsNumFront;i++)
        seats.push(new Seat((i * xPad) + 300, value, 30, 30, id++, ch, i, "#998515"));   
}


var num = 3, start = 60, diff = 40, ch = 'A';
for(var i = 0;i < num;i++){
              //Calculates position based on input parameters 
    addSeats(start + (diff * i),  ch++);
}
//The for-loop above will generate seats with the following values (60, 'A'), (100, 'B'), (140, 'C').

The provided code should be adaptable to any positive values of num.

Answer №2

When you parameterize your push statement, you have the flexibility to input values as necessary. Taking inspiration from your for loop example with a switch case added, there are various approaches to achieve the same goal of writing the for loop just once.

Here's an elaborate illustration of what you might want to accomplish:

var num = 3
var param1 = 0;
var param2 = "";

for (x = 0; x <= seatsNumFront; x++) {
    switch (num) {
        case 1:
            param1 = 60;
            param2 = "A";
            break;
        case 2:
            param1 = 100;
            param2 = "B";
            break;
        case 3:
            param1 = 140;
            param2 = "C";
            break;
        default:
    }
    //seats.push(new Seat((c * xPad) + 300, 140, 30, 30, id++, "C", c, "#998515"))
    seats.push(new Seat((x * xPad) + 300, param1, 30, 30, id++, param2, x, "#998515"))
}

In this scenario, if num is equal to 3, then the resulting for loop will function equivalently to this:

seats.push(new Seat((c * xPad) + 300, 140, 30, 30, id++, "C", c, "#998515"))

By assigning the value of 140 to param1 and "C" to param2. If num was 2, it would utilize 100 and "B" accordingly.

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

Issue: Unable to use the b.replace function as it is not recognized (first time encountering this error)

I can't seem to figure out what I'm doing wrong. It feels like such a silly mistake, and I was hoping someone could lend a hand in solving it. Here is my controller - I'm utilizing ng-file-upload, where Upload is sourced from: .controller( ...

comparing multiple values separated by commas with JavaScript

I need validation using a comma-separated value format. Within the illustration, there are two fields: "Saloon Price" (value: 10,10,10,10) and "Saloon Offer Price" (value: 11,11,11,11). The first value must be less than the second. Saloon price Value & ...

The error message "Unexpected node environment at this time" occurred unexpectedly

I am currently watching a tutorial on YouTube to enhance my knowledge of Node.js and Express. To enable the use of nodemon, I made modifications to my package.json file as shown below: package.json "scripts": { "start": "if [[ $NODE_ENV == 'p ...

Utilizing Ajax to dynamically load files within the Django framework

My current project involves working with Django, specifically a feature that requires loading a file and displaying its content in a textarea. Instead of storing the file on the server side or in a database, I am exploring the use of AJAX to send the file ...

What is the best way to darken the background when an alert is displayed and disable the dimming effect when the alert is closed?

Here's the JavaScript snippet I'm using: reset.addEventListener("click", function(){ document.querySelector("#body").classList.add("darkenPage"); myReset(); alert("Reset Successful!!"); document.querySelector("#body").classList.re ...

Troubleshooting the non-functional asynchronous function

After starting to use redis with node (specifically the node_redis module), I decided to wrap my retrieval code for debugging and DRY principles. However, I encountered an issue where my new function wasn't working as expected. As someone who is stil ...

Generating an HTML table with JSON data in JavaScript

I'm still struggling with JavaScript as a beginner, so please bear with me and provide guidance step by step. Also, try to avoid overwhelming the comments with links as it confuses me. This is an attempt to bypass the CORS issue. <!D ...

Discover the array of results by implementing a while loop in JavaScript

My goal is to create a list of outputs that are not evenly divisible by numbers smaller than the input value. For example, if the input value is 10, the list should be 10, 9, 8, 7, 6, 4, 3, 1. I have written some code in JavaScript for this purpose, but ...

ReactJS is making a controlled input of type text into an uncontrolled component with the help of a component transformation

I am encountering a situation where I fetch data from the server and set values in the state for controlled inputs. For example, if I have an input field with a value of this.state.name, I retrieve the name "Dave" from the server and set it in the state as ...

Having trouble replicating the progressive response from the server in node.js

Hey there, I recently dipped my toes into the world of node.js and decided to give it a shot. Following Ryan Dahl's tutorial (http://www.youtube.com/watch?v=jo_B4LTHi3I) as my starting point, I reached a section around 0:17:00 where he explains how s ...

What is the best way to transmit error messages from the server to the client?

I am currently working on my express server and I have a query regarding how to efficiently communicate error messages to the client side. My goal is to display the error message both on the client console as well as on the server console, but I am uncerta ...

How come I am receiving the E11000 error from Mongo when I have not designated any field as unique?

Encountering an issue while attempting to save the second document to MongoDB Atlas. The error message reads as follows: Error:MongoError: E11000 duplicate key error collection: test.orders index: orderId_1 dup key: { orderId: null } Despite having no un ...

Retrieving a attribute from an element on a separate webpage

On my website, I have a list of links that use ajax to load new pages. Each of these new pages features a gallery of images with a main image. I am trying to figure out how to extract the source URL from the main image in order to display it as a thumbn ...

changing the css transformation into zoom and positioning

My goal is to incorporate pinch zoom and panning using hardware-accelerated CSS properties like transform: translate3d() scale3d(). After completing the gesture, I reset the transform and switch to CSS zoom along with absolute positioning. This method ensu ...

Top method for identifying "abandoned words" within text that has been wrapped

Our content and design teams have a specific request to prevent paragraphs from ending with an "orphan word" - a single word on the last line of text that has wrapped onto multiple lines. The designer's proposed solution is to adjust the margins sligh ...

Issue with Bootstrap jQuery dynamic table edit/delete/view button functionality not functioning as expected

Could really use some assistance with this issue. I have a DataTable that includes a button in the last column which offers options like Edit/Delete/View. When clicked, it should delete the entire row. However, I'm struggling to access the current ele ...

What is the solution for resolving the problem of the cursor jumping to the end when converting numbers in JavaScript?

After exploring the inquiries regarding converting digits in JavaScript, such as What's the solution and the right way to convert digits in JavaScript? and How to convert numbers in JavaScript, and problems with commands to remove non-numeric characte ...

Form submission is not functioning as expected

I am having trouble with my form submission. When I try to submit the form, nothing happens. I have tried various solutions but have not been able to resolve the issue. I have reviewed all available resources but still cannot figure out why my code is not ...

Is there a way to load all movies in advance when none of the tags are selected?

In my current project, I am working on a feature that involves an array of movie objects. Each movie has a name and tags assigned to it. I want to be able to display movies based on the tags selected by the user. For example, if the user selects the tag "c ...

Fluid sifting and interactive webpage

I'm almost done with my website, but I'm facing a problem. There are 3 blocks of text on my page - 2 static and 1 dynamic. When I click a button, the page should change, which is working fine. However, when I added smooth scroll to the website, ...