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

"Encountered an issue while serializing the user for session storage in Passport.js. Have you already implemented code for

I have recently started learning nodejs and I am currently working on creating a login system. I followed the code for serializing the user from the passport documentation and placed it in config/passport.js. However, I keep encountering the error "Failed ...

delaying the alteration of an image attribute following an AJAX call

After clicking on a button, a function is triggered (think of it as a published/unpublished button). Immediately after the function is activated, I change the element to display a loader gif. function updateStatus(event, status, element, data, action) { ...

Is the behavior of String.replace with / and different in Node.js compared to Chrome?

Creating a router in Node.js involves mapping URIs to actions, which requires an easily configurable list of URIs and regular expressions to match against the request URI. This process may seem familiar if you have experience with PHP. To test this functi ...

Challenge with executing javascript library (photo sphere viewer)

I was excited to incorporate Photo Sphere Viewer into my project. After running npm i photo-sphere-viewer I noticed that the modules were successfully downloaded. Following that, I added this line inside my project: import PhotoSphereViewer from ' ...

Something is seriously wrong with the datetime in fullcalendar JavaScript

I've been diving into a tutorial for creating a calendar scheduler in asp.net MVC5 from this link. One issue I'm facing is the datetime being passed and stored as the min value in the database (1/1/0001 12:00:00 AM), almost like it's null b ...

Typing in Text within Kendo Textbox using Protractor

I'm encountering an issue with Protractor while trying to input text into a Kendo TextBox. The error message I receive is "ElementNotVisibleError: element not visible". Interestingly, when the text box is clicked on, the "style="display: none;" change ...

Display a component by selecting a hyperlink in React

Currently working on a story in my storytelling, which might not be too important for the question I have. What I am trying to accomplish is creating a scenario where there is an anchor tag that, once clicked, triggers the opening of a dialog box or modal ...

Here's a step-by-step guide on how to parse JSON information in JavaScript when it's formatted as key-value

I need to parse the JSON data in JavaScript. The data consists of key-value pairs. Data looks like this: {09/02/2014 15:36:25=[33.82, 33.42, 40.83], 08/11/2014 16:25:15=[36.6, 33.42, 40.45], 07/30/2014 08:43:57=[0.0, 0.0, 0.0], 08/12/2014 22:00:52=[77.99 ...

Is there a way to successfully implement mouseover/mouseout functionalities while also resizing?

I've been working on a dropdown menu that functions well on both mobile and desktop devices. However, I have encountered an issue with resizing. Even when the screen size is reduced to mobile dimensions, the mouseover and mouseout functions continue t ...

Using JavaScript within WordPress to achieve a seamless scrolling effect

I am seeking to implement a Smooth Scroll effect on my website located at . The site is built on WordPress and I am facing difficulty in connecting JavaScript/jQuery in WordPress. I have come across various WordPress plugins, but they either do not meet my ...

Utilizing a JavaScript variable within a jQuery function as an attribute

var image = "path.png"; Is it possible to include the 'image' variable in the jQuery function like this? $('#mapfoto').prepend('<img id="theImg" src="http://path.gr/" + image />'); ...

Is it possible to incorporate Vector4's into the geometry of three.js?

Exploring the functionalities of the three.js library has been a fascinating journey for me. As I delve into the intricacies, I've come to understand that the coordinates stored in a mesh's geometry are tuples consisting of (x,y,z). However, bene ...

Issues arise when attempting to smoothly scroll to an anchor point in a webpage

While working on my website, I have encountered a challenge. The issue arises when dealing with multiple div items. Upon scrolling slightly, the entire page focuses on the div with a height of 100vh, which works perfectly fine. However, my attempts to ...

Create a new tab without triggering the pop-up blocker by utilizing an iframe's JavaScript event

I currently have an iframe embedded in a webpage. Once data is successfully sent to the server within the iframe, the server responds with a new URL to be opened either in a new tab or the parent window. The main issue I am encountering is that the brows ...

employing express.json() post raw-body

Within my Express application, I am aiming to validate the length of the request body and restrict it irrespective of the content type. Additionally, I wish to parse the body only if the content type is JSON. How can I go about accomplishing this? Curren ...

Pressing the button results in no action

I am currently developing a program that randomly selects 5 words from a database and inserts them into an array. Although the page loads correctly initially, nothing happens when the button is clicked. None of the alerts are triggered, suggesting that the ...

Transforming seconds into years, months, weeks, days, hours, minutes, and seconds

Can anyone help me modify Andris’ solution from this post: Convert seconds to days, hours, minutes and seconds to also include years, months, and weeks? I am currently running this code: getDateStrings() { console.log(req_creation_date); const toda ...

Creating an array of objects sorted in alphabetical order

My task involves working with an array of objects that each have a name property: var myList = [{ name: 'Apple' }, { name: 'Nervousness', }, { name: 'Dry' }, { name: 'Assign' }, { name: 'Date' }] ...

What method can I use to identify the most widely-used edition of a specific npm module?

While the npm registry does provide metrics on the most depended packages, have you ever wondered if it's possible to determine the most popular version of a specific package? For example, as a user considering upgrading to react-router^4.0.0, wouldn ...

What is the most effective method for destructuring within React components?

Observing how people implement destructuring in functional components in React, I have noticed a common pattern. const InputGroup = ({ name, placeholder, value }) => ( However, my preferred method differs: const InputGroup = props => { ...