Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Mar 2012
    Posts
    60
    Thanks
    65
    Thanked 0 Times in 0 Posts

    Inside loop only do something every forth time

    Hi


    I have an array and want to insert "--" in between every 4th number - how do i do this?

    Thanks


    Code:
    var arr = {1,2,3,4,5,6,7,8,9};
    
    var n = "";
    
    for (var i=1 ; i<= arr.length ; i ++){
    
         n += arr[i].toString();
    
        if( if the forth loop ){
    
               n += "--"; //only add this every 4 loops
    
        }
    
    }
    
    alert(n);   //wanted result  1234--5678--9

  • #2
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    Code:
    var arr = [ 1,2,3,4,5,6,7,8,9 ];
    var n = "";
    for (var i = 0; i < arr.length; i++) {
        n += arr[i];
        if(((i + 1) % 4) == 0) {
            n += "--"; //only add this every 4 loops
        }
    }
    alert(n);   //wanted result  1234--5678--9
    "Anything that is complex is not useful and anything that is useful is simple. This has been my whole life's motto." -- Mikhail T. Kalashnikov

  • Users who have thanked Krupski for this post:

    code-in-time (05-31-2012)

  • #3
    New Coder
    Join Date
    Mar 2012
    Posts
    60
    Thanks
    65
    Thanked 0 Times in 0 Posts
    thanks

    what does the % mean?

  • #4
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,628
    Thanks
    0
    Thanked 648 Times in 638 Posts
    % means remainder or modulo

    1%4 = 1
    2%4 = 2
    3%4 = 4
    4%4 = 0
    5%4 = 1
    6%4 = 2
    7%4 = 3
    8%4 = 0
    9%4 = 1

    and so on -so if you increment the nember on the left by one every time the result will be zero when that number is exactly divisible by 4 - ie every fourth time.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    code-in-time (06-12-2012)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •