Question

i have two simple regular for loops.

for (var i=0; i<images.xAxis.length; i++){
  for (var x=0; x<images.yAxis.length; x++){
    //return number from 0 to 9
    imgNumber = images.xAxis.length*i+x;
    addImage(imgNumber);
  }
}

Well it is not returning number from 0 to 9. instead it returning :

1
2
3
-
2
4
6
-
3
6
9

Assuming that i don't want to use helper variable like:

idx+=1;

i want to use x and i in some math expression.

Thanks!

Was it helpful?

Solution

What you are basically trying to do with those nested loops is, how to convert a number in base 3 to a number in base 10. The way to do it is:

for (var i=0; i<3; i++){
  for (var x=0; x<3; x++){
   //return number from 0 to 9
     addImage(3*i+x);
  }
}

EDIT With your edit, the code becomes

for (var x=0; x<images.xAxis.length; x++){
  for (var y=0; y<images.yAxis.length; y++){
    //return number from 0 to 9
    imgNumber = images.xAxis.length*i+x;
    addImage(imgNumber);
  }
}

OTHER TIPS

You can try using:-

 for (var i=0; i<3; i++){
   for (var x=0; x<3; x++){
      imgNumber = i * 3 + x;
      addImage(imgNumber);
    }
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top