1

I've got a loop which returns a list of image sources with incremental values. When testing I was using 4 digit values with leading zeros due to the image src's.

The strange thing I noticed is that if I use a leading zero on the condition in the loop it stops at 398. If I remove this zero it completes correctly.

// Stops at 398
for (var i = 0001; i < 0617; i++) {
  $('.target').append('{"src": "IMG_' + i + '.jpg", "id":"image' + i + '"}');
}

// Completes
for (var i = 0001; i < 617; i++) {
  $('.target').append('{"src": "IMG_' + i + '.jpg", "id":"image' + i + '"}');
}

Here's a fiddle with a working example

Has anyone got any insight into this behaviour?

Adam Hughes
  • 2,197
  • 20
  • 31
  • 2
    0617 is octal value. Its decimal value is 399. – Cem Ekici Feb 02 '16 at 11:27
  • 1
    Apart from the octal thing, why are you using leading zeros anyway for this purpose? For the img src, you would be better off [padding the numbers](http://stackoverflow.com/questions/10073699/pad-a-number-with-leading-zeros-in-javascript). – Abhitalks Feb 02 '16 at 11:27
  • @Abhitalks Am I padding the numbers. I didn't provide the full source because I just wanted to know about this specific issue that I noticed – Adam Hughes Feb 02 '16 at 11:39
  • Did you notice that the leading zeros do not appear in your output? You are setting i to a *number*, not a string, so leading zeros are not retained. (Even aside from the octal issue, which doesn't affect the starting value of 1.) – nnnnnn Feb 02 '16 at 11:41
  • @nnnnnn Again - Not the issue. I removed a lot of code just for this example. I just wanted to know why it stopped at 398 – Adam Hughes Feb 02 '16 at 11:44

2 Answers2

3

Number in javascript with leading zeroes is an octal number.

Read more about it here: http://www.javascripter.net/faq/octalsan.htm

Are
  • 2,160
  • 1
  • 21
  • 31
0

A simple way to do this is just to add the zeros as text. I updated your fiddle with those two lines:

var number = i;
if (number<=9999) { number = ("000"+number).slice(-4); }

You can find it here: https://jsfiddle.net/16p455z7/2/

Gerard Cuadras
  • 1,655
  • 1
  • 17
  • 23