Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Can For/In Loop have Index Start From 5?

1. ## 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.

• 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;
}```

• 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;```

•

#### Posting Permissions

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