admin管理员组

文章数量:1302352

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 = '';
    }
}

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 = '';
    }
}
Share edited Sep 4, 2015 at 11:32 Armali 19.4k14 gold badges61 silver badges184 bronze badges asked Sep 4, 2015 at 11:18 mamadymamady 1781 gold badge1 silver badge11 bronze badges 3
  • 1 Your code is missing a } btw. – Andy Commented Sep 4, 2015 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 Commented Sep 4, 2015 at 11:23
  • possible duplicate of What is the most efficient way to reverse an array in Javascript? – romuleald Commented Sep 4, 2015 at 11:29
Add a ment  | 

2 Answers 2

Reset to default 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 = '';
}
for (var i = nb; i >= 1; i--) {
  // do something
}

本文标签: javascript(JS) make forloop function go from last to firstStack Overflow