...

View Full Version : Can For/In Loop have Index Start From 5?



dealmaker
12-14-2005, 06:26 PM
Hi,
I want to fill the array with 1s starting with index 5. Can I do that like below?



i=5;
for(i in myarray)
myarray[i] = 1;


Many thanks.

fci
12-14-2005, 06:33 PM
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:


Array.fill_by_offset = function(i, total, val) {
var arr = []
total += i + 1;
while (i<total)
arr[i++] = val;
return arr;
}

liorean
12-14-2005, 06:40 PM
No. The for..in index will be given the name of each key. You could exclude based on those keys:
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
var
i=5,
l=myarray.length;
while(i<l)
myarray[i++]=1;or, if you feel more comforable with that,
for(var i=5,l=myarray.length;i<l;i++)
myarray[i]=1;



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum