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
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);
It returns undefined because you are setting the array length with set.length. When this is called, all elements of the array are undefined
I'd remove the set.length line altogether.
Updated code
var set = [];
for (i = 0; i <= 50; i++) {
set.push(Math.floor(Math.random() * 500))
}
console.log(set)
=> [138, 215, 149, 180, 348, 497, 88, 156, 238, 439, 130, 185, 20, 116, 330, 131, 188, 257,
260, 1, 469, 482, 208, 494, 26, 374, 281, 403, 403, 137, 156, 243, 378, 281, 329,
84, 471, 429, 120, 381, 456, 471, 36, 395, 299, 497, 151, 210, 80, 310]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With