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 sounds to me like you want to create a static sized array with dynamic content. If this is the case, you need to create the array with the proper size first. That would create the array for you. However, you could auto-populate the array with the random values you wanted like so:
var N = 50;
var set = Array.apply(null, {length: N}).map(Function.call, Math.random);
Once the array is auto-populated, the rest of your code should work as expected, by simply using the value of the random number in the array so:
for(var i in set){
set[i] = Math.floor(set[i] * 500) + 1;
}
console.log(set);
// OUTPUT
// [267, 219, 293, 298, 403, 70, 162, 270, 434, 292, 433, 478, 476,
// 311, 268, 266, 105, 242, 255, 250, 206, 104, 142, 406, 50, 139,
// 364, 375, 47, 480, 445, 149, 91, 228, 404, 267, 298, 158, 305,
// 311, 92, 377, 490, 65, 149, 431, 28, 452, 353, 494]
This is where I got this: Create a JavaScript array containing 1...N