0

I have files name animation_00000.png through to animation_00256.png. I thought I would be able to simple loop through and load them to screen like this,

var animation = $("<img id='animtation' />");
animation.prependTo(".stage");

for(var i = 00000; i < 00276; i++)
{
    animation.attr("src", "img/animations/cat/Catwalk_"+i+".png");
}

However this tries to load the image sources like this,

Catwalk_0.png

How can I make sure that all the zeroes are preserved in the count?

Kristiono Setyadi
  • 5,635
  • 1
  • 19
  • 29
Udders
  • 6,914
  • 24
  • 102
  • 194

4 Answers4

2

something like this:

var num = "00000"+ i.toString();
var str = num.substr(num.length-5,5);
animation.attr("src", "img/animations/cat/Catwalk_"+ str +".png");
rene
  • 41,474
  • 78
  • 114
  • 152
1

Literals do not maintain their lexical representation when converted into strings. Or, in fact, after your script is parsed for execution. So those leading zeroes are gone. They also make your literals be interpreted as octals rather than decimals, which you certainly don't want here.

Instead, drop the leading zeroes, and use a string-padding function inside the loop body. There's no built-in such function, but it's fairly trivial to write one.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

There's no built in function for padding numbers. So, try something like this

function padding (number, maximum) 
{
  return number.length < maximum ? padding("0" + number, maximum) : number;
}

Then, change your loop to look like

for(var i = 0; i < 276; i++)
{
   padded = padding(i, 5);
   animation.attr("src", "img/animations/cat/Catwalk_"+padded+".png");
}
Terence Eden
  • 14,034
  • 3
  • 48
  • 89
0
var iString = i.toString();

if(i < 10){
    iString = "0" + iString
}
if(i < 100){
    iString = "0" + iString
}
if(i < 1000){
    iString = "0" + iString
}
if(i < 10000){
    iString = "0" + iString
}
if(i < 100000){
    iString = "0" + iString
}

i'm not really sure about if this will work becuase i ame not an expert in JS. but this is how i solve this problem in most other code lang.

Life of Madness
  • 784
  • 1
  • 5
  • 21