2

I'm trying to write an array of images, but I have a lot of images so I'm trying to use "for loop" to generate it.

my current code is :

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 more images to add. so I would like to know how to use for loop to generate this.

The last image is /images/image3360.png

Thank you!

Yaya Adam
  • 25
  • 3

3 Answers3

3

I think you don't want to generate the actual images, but rather fill an array with filenames. The simplest way would be:

const MAX = 3360;
const PREFIX = "/images/image";
const EXT = ".png";
const arr = [];
for (let i = 0; i <= MAX; i += 5) {
  arr.push(
    PREFIX + ("0000" + i).slice(-4) + EXT
  );
}

The slice thing comes from this answer.

Maciej B. Nowak
  • 1,180
  • 7
  • 19
  • And why exactly is that? – Maciej B. Nowak Dec 23 '19 at 13:26
  • sorry, my fault. Didn't see that you were slicing the string. Reasonable solution indeed, assuming the "jump" criteria to 3360 is actually numeric. – briosheje Dec 23 '19 at 13:27
  • Indeed, but given the brevity of this question one must make some assumptions. – Maciej B. Nowak Dec 23 '19 at 13:29
  • I known, though I personally think there are **not** enough informations to properly answer to the question. In any case, you deserve a +1 for the brevity of your answer and for the clever usage of slice, definitely the most suitable solution for that scenario, in my opinion. – briosheje Dec 23 '19 at 13:33
1

const step = 5; // Steps
const imgNumber = 3360/step; // Image number
const images = []; // Array to hold images


for(i = 0; i<=imgNumber; i++) {
   const currNum = i*step; // Calculate suffix
   let str = "/images/image0000";
   str = str.substring(0, str.length - currNum.toString().length); // Compile number
   images.push(`${str}${currNum}.png`); // Store the image in the array
}
console.log(images);
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
0

You can do it like this:

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

    for (let j = 0; j < numberOfZeros; j++) {
        imageString += "0";
    }
    images.push("/images/image" + imageString + i.toString() + ".png");
}

This essentially runs a for loop which increments by 5 each time, calculates the amount of leading zeros needed, then runs another for loop to add these leading zeros, and inserts a concatenation of this and the actual number inside the string which gets pushed to the array.

Justin Feakes
  • 380
  • 1
  • 7