Creating a series of images in JavaScript using a for loop

Currently attempting to create an array of images, but with a large number of images I am looking into using a "for loop" for generation.

Here is my current code snippet :

var images = [
    "/images/image0000.png",
    "/images/image0005.png",
    "/images/image0010.png",
    "/images/image0015.png",
    "/images/image0020.png",
    "/images/image0025.png",
    "/images/image0030.png",
    "/images/image0040.png",
    "/images/image0045.png",
    "/images/image0050.png"
];

I have additional images to include. Can you advise me on utilizing a for loop to accomplish this task?

The final image in the sequence is /images/image3360.png

Appreciate your assistance!

Answer №1

To avoid generating actual images, you can instead store file names in an array. Here is a simple method to achieve this:

const MAX = 2560;
const PREFIX = "/photos/photo";
const EXTENSION = ".jpg";
const imageArray = [];
for (let index = 0; index <= MAX; index += 4) {
  imageArray.push(
    PREFIX + ("0000" + index).slice(-4) + EXTENSION
  );
}

The usage of the slice function is derived from this previous solution.

Answer №2

const increment = 5; // Increment value
const totalImages = 3360/increment; // Total number of images
const imageArray = []; // Array to store images


for(i = 0; i<=totalImages; i++) {
   const currentNum = i*increment; // Calculate suffix
   let string = "/images/image0000";
   string = string.substring(0, string.length - currentNum.toString().length); // Compile number
   imageArray.push(`${string}${currentNum}.png`); // Add the image to the array
}
console.log(imageArray);

Answer №3

Here is a method to achieve the same result:

const images = [];
for (let i = 0; i <= 3360; i += 5) {
    let imageStr = "";
    let numZeros = 4 - i.toString().length;

    for (let j = 0; j < numZeros; j++) {
        imageStr += "0";
    }
    images.push("/photos/photo" + imageStr + i.toString() + ".jpg");
}

This code snippet utilizes a for loop that iterates by 5, calculates the necessary leading zeros, and appends them to form the desired image string pushed into the array.

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

jQuery draggable elements can be easily dropped onto droppable areas and sorted

I need help with arranging the words in the bottom tiles by sorting them from "Most Like Me" to "Least Like Me" droppable areas. Currently, I am able to drag and drop the words into different boxes, but it ends up stacking two draggable items on top of eac ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

The initial setting of [opened]="true" causes an issue with the Angular Material date range picker

Recently, we completed the upgrade of our app from Angular 14 to 15.2.9, which includes Angular Material. The migration process went smoothly, and now our app is compiling and running without any errors. However, we encountered an issue with the mat-date-r ...

Fill in datatable with information from a JSON array if there are missing values in certain columns

My goal is to populate a datatable in JavaScript. Currently, I am able to do so, but some of the last rows have blank columns which are populated first. I attempted to fill those blank columns, and then the data populates in order. Here is an example of my ...

What Are the Possible Use Cases for Template Engine in Angular 2?

For the development of a large single page application (SPA) with Angular 2.0, I have decided to utilize a template engine like JADE/PUG in order to enhance clarity and clean up the code. My goal is to achieve optimal performance for the application. Th ...

What could be causing the delay in response times from these unpredictable APIs within the Express server?

We are currently experiencing performance issues with our Express.js server and MongoDB database. Randomly, some API requests are taking too long to respond or timing out throughout the day. Our application is in production, hosted on two AWS instances wit ...

reqParam = $.getQueryParameters(); How does this request work within an ajax form

I've spent a lot of time searching, but I can't figure out what the code reqParam = $.getQueryParameters(); means and how it is used in Ajax JavaScript. I copied this Java script from a website as an example. If anyone has any insights, please he ...

Why is my JQuery UI droppable accept condition failing to work?

After scouring the internet for hours, I'm still stuck and can't seem to figure out what's wrong with my code: Here's the HTML snippet: <ul style="list-style:none;cursor:default;"> <li>uuu</li> <li>aaa& ...

The dropdown menu is malfunctioning when accessed within the mobile view of a jQuery

Take a look at this code snippet on Fiddle: https://jsfiddle.net/rizwanali98601/ngofhc24/12/. The table below contains a dropdown inside a jQuery Datatable. When the button is clicked, an option is supposed to be added to the dropdown. However, in mobile ...

Sending a JSON array in an AJAX request results in receiving null values in an MVC application

I've been trying to send an array of JSON objects to my controller action, but it keeps showing up as null. Here's the JavaScript code I'm using: function UpdateSelected() { var items = {}; //Loop through grid / sub grids and crea ...

Is there a way to selectively include a filter in ng-repeat within a directive?

Utilizing an element directive across multiple views, the directive iterates through each 'resource' in a list of resources using ng-repeat="resource in resources". Different page controllers determine which resources are fetched from the API by ...

What is the best way to link a newly created contact to the current user in Mongoose?

I'm faced with the challenge of creating a contact that is specifically added to the current user's contact array. Currently, my controller only creates a generic contact and doesn't cater to the individual user. Controller: function cont ...

Utilize load-grunt-configs and run bower.install() with grunt

I have been attempting to break down my current Gruntfile into smaller parts for better clarity. However, I have encountered a hurdle while using bower.install to manage project dependencies. My directory structure appears as follows: package.json bower.j ...

Choose Your Preferences When the Page Loads

I have a dropdown menu where I can select multiple options at once without checkboxes. When the page loads, I want all of the options to be pre-selected by default. I am aware that I can use $(document).ready() to trigger actions after the page has load ...

Validating an Element Directive in AngularJS: A Step-by-Step Guide

I have developed a directive for handling numbers function numberInputDirective() { return { restrict: 'E', scope: { model: '=', disabled: '=?', decimals: ...

Development of Chrome Extensions, JavaScript dilemma

Hey there, I'm new to JavaScript and I've been diving into the world of creating Chrome extensions. I'm trying to set up a content script and browser action, but I'm struggling to get it up and running. I know I'm probably making a ...

Guide to retrieve the file name into a text box upon selection (Avoid displaying as c:/fake path/)

I am trying to achieve the functionality where after choosing a file in a file input, the file name is automatically displayed in a text box named file_name without needing to click or submit any button. Unfortunately, I have been unable to find the correc ...

Combining PHP JQuery Dialog with Datatables results in a sleek design loss

Recently, I encountered an issue with my code. I have a file called incident_view.php which pulls data from the database and displays it using Datatables. Everything was working fine until I tried to open this page in a JQuery dialog on another page called ...

Having trouble utilizing the DatePicker component in my react native application

I've encountered an issue while using DatePicker in react native. Whenever I try to use it, an error pops up saying: "render error a date or time must be specified as value prop". Here is the link to my repository: my github repository const [date, se ...

Extending a Typescript class from another file

I have a total of three classes spread across three separate .ts files - ClassA, ClassB, and ClassC. Firstly, in the initial file (file a.ts), I have: //file a.ts class ClassA { } The second file contains: //file b.ts export class ClassB extends Class ...