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 = '';
    }
}
3
  • 1
    Your code is missing a } btw. 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;) { .. } Commented Sep 4, 2015 at 11:23
  • possible duplicate of What is the most efficient way to reverse an array in Javascript? Commented Sep 4, 2015 at 11:29

2 Answers 2

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 = '';
}
Sign up to request clarification or add additional context in comments.

4 Comments

Question.. Now it thinks 4 is first and adds +first+ to the class, How can I make 1 first so 1 will get +first+ class?
Use if statement in loop to check and add
Would you please show me like I have no JS knowledge (because I don't!)
I tried for (var i = nb; i > 0; i--) { if (i = 1) { first = ''; } } but it doesn't work
0
for (var i = nb; i >= 1; i--) {
  // do something
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.