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 3 of 3
  1. #1
    Regular Coder
    Join Date
    Jul 2005
    Posts
    342
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Can For/In Loop have Index Start From 5?

    Hi,
    I want to fill the array with 1s starting with index 5. Can I do that like below?

    Code:
    i=5;
    for(i in myarray) 
      myarray[i] = 1;
    Many thanks.

  • #2
    fci
    fci is offline
    Senior Coder
    Join Date
    Aug 2004
    Location
    Twin Cities
    Posts
    1,345
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Code:
    Array.fill_by_offset = function(start, total, val) {
        var arr = []
        total += start;
        for (var i=start; i<=total; i++)
            arr[i] = val;
        return arr;
    }
    var filled_arr = Array.fill_by_offset(5, 5, 1)
    for (var i in filled_arr)
        alert(i + ": " + filled_arr[i])
    tweaked to use while loop(more optimal) as suggested in liorean's post:
    Code:
    Array.fill_by_offset = function(i, total, val) {
        var arr = []
        total += i + 1;
        while (i<total) 
            arr[i++] = val;
        return arr;
    }
    Last edited by fci; 12-14-2005 at 06:53 PM.

  • #3
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    No. The for..in index will be given the name of each key. You could exclude based on those keys:
    Code:
    var
        i;
    for(i in myarray)
        if(i<5)
            continue;
        else
            myarray[i]=1;
    However, that is a bad way to code it. The for..in loop isn't made for iterating over arrays, it's made for iterating over object properties. As evidenced by the fact it will iterate also over non-integer key values. And as evidenced by the fact it's much slower than a regular loop for this purpose as long as the array is relatively dense. A much better way to loop would be
    Code:
    var
        i=5,
        l=myarray.length;
    while(i<l)
        myarray[i++]=1;
    or, if you feel more comforable with that,
    Code:
    for(var i=5,l=myarray.length;i<l;i++)
        myarray[i]=1;
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards


  •  

    Posting Permissions

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