Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  6] [ 5]  / answers: 1 / hits: 26679  / 9 Years ago, tue, may 19, 2015, 12:00:00

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);

More From » arrays

 Answers
168

The second link seems to have your answer.



The for (var item in array) looks at your array and, for each item in the array, stores that item in item and lets you iterate over each item. Setting the array.length does not give you any items in the array, and thus the for in does not execute at all - there is nothing to iterate over.


[#66540] Monday, May 18, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
danalexc

Total Points: 114
Total Questions: 119
Total Answers: 103

Location: Hungary
Member since Wed, Nov 9, 2022
2 Years ago
;