1

I have a set of variables in my code.

var image1Index = 0;
var image2Index = 1;
var image3Index = 2;
var image4Index = 3;
var image5Index = 4;
var image6Index = 5;
var image7Index = 6;
var image8Index = 7;
var image9Index = 8;
var image10Index = 9;

I use those variables to make it more easy to change the values without the need of changing to mutch in the rest of my code. The problem i encounter is that i keep repeating myself.

So do i have a function for setting the right value of the variables.

function setCorrectIndexDown(index,place){
  var numberOfPlaceholders = 10
  if ((index - numberOfPlaceholders) < place){
    return  place;
  }
  else{
    return  (index - numberOfPlaceholders) %  imageArray.length ;
  }
}

After that i use this function for every variable.

image1Index = setCorrectIndexDown(image1Index,0);
image2Index = setCorrectIndexDown(image2Index,1);
image3Index = setCorrectIndexDown(image3Index,2);
image4Index = setCorrectIndexDown(image4Index,3);
image5Index = setCorrectIndexDown(image5Index,4);
image6Index = setCorrectIndexDown(image6Index,5);
image7Index = setCorrectIndexDown(image7Index,6);
image8Index = setCorrectIndexDown(image8Index,7);
image9Index = setCorrectIndexDown(image9Index,8);
image10Index = setCorrectIndexDown(image10Index,9);

As you see do i repeat myself a lot this way. I am searching for a way to make this shorter and do the same in just a few lines without the need to repeat myself to mutch.

A few days ago I found the eval() function, this did seem like my solution since i could wrap stuff in a string and change this string in a loop like this

for(i = 0; i < 10; i++){
  eval(`image${i+1}Index = setCorrectImageDown(image${i+1}Index, i)`);
}

But then I did read about the risks so decided not to use eval() for my goals.

So if I wont use eval what is the most practical way to do the same thing in a few lines instead of a repeating line of code?

Thanks in advance for the help and advice.

Adri
  • 13
  • 5

0 Answers0