4

This code is now making 1 to 4. How can it make 4 to 1 (last to first)?

var nb = 4;
var first = ' active';
if (nb > 1) {
    for (var i = 1; i <= nb; i++) {
        page  = page+'<span class="to-step-nb'+first+'">'+0+String(i)+'</span>';
        first = '';
    }
}
Armali
  • 18,255
  • 14
  • 57
  • 171
mamady
  • 180
  • 1
  • 11
  • 1
    Your code is missing a `}` btw. – Andy Sep 04 '15 at 11:21
  • There are a thousand ways to loop backwards, and I'm sure you could have googled it a lot faster than the time it took to write the question, but here you go, my favorite backwards loop: `for(var i=len;i-->1;) { .. }` – Jite Sep 04 '15 at 11:23
  • possible duplicate of [What is the most efficient way to reverse an array in Javascript?](http://stackoverflow.com/questions/5276953/what-is-the-most-efficient-way-to-reverse-an-array-in-javascript) – romuleald Sep 04 '15 at 11:29

2 Answers2

8
  1. nb should be number not string
  2. You're missing } at the end
  3. Use the condition

    for (var i = nb; i > 0; i--)
    

    to reverse the loop.

  4. String(i) is not required

  5. first is set to empty string, after first iteration, so now, you'll have last item active

  6. if (nb > 1), is not required, as if the condition fails, for will not execute

  7. You can use Shorthand for a = a + .. as a += ..

Code:

var nb = 4;
var first = ' active';

for (var i = nb; i > 0; i--) {
    page += '<span class="to-step-nb' + first + '">' + 0 + i + '</span>';
    first = '';
}
Tushar
  • 85,780
  • 21
  • 159
  • 179
0
for (var i = nb; i >= 1; i--) {
  // do something
}
Vittorio
  • 11
  • 4