To return an array set
with a sequence of random numbers between 1 and 500 I tried to refactor a standard for loop for(var i = 0; i< 50; i++)
and that worked but when I tried to do a refactor using a for in
loop it doesn't. My guess is that there is something about the array.length
property and it's use that I'm screwing up.
TL;DR Why does this return an array of 50 undefined elements rather than an array of 50 random integers? And is there a way to make this approach work?
var set = [];
set.length = 50;
for(var i in set){
set[i] = Math.floor((Math.random() * 500) + 1);
}
console.log(set);
Similar Questions: Helpful but not quite what I'm looking for
Update
As I suspected the point I was missing is that setting set.length
doesn't add elements to the array it only creates a sparse array (an array with gaps). In my case you cannot use for in
because there isn't anything in the array to iterate over. I would either have to populate the array with dummy content(i.e. empty strings) or, more logically, separate the range part I tried to implement with the .length
property into a separate range
variable.
Working version
var set = [], range = 50;
for(var i = 0; i < range; i++){
set[i]=Math.floor((Math.random() * 500) + 1);
}
console.log(set);