I’m randomly generating numbers inside of an array.
Here’s my code:
var max = 10,
lowest = 1,
store = [];
while(store.length < max) {
var values = Math.floor(Math.random() * max) + 1;
if(store.indexOf(values) === -1) {
store.push(values);
}
}
store;
The code works perfectly fine, but when I move the values variable outside of the while-loop and declare it above the while loop scope, it causes an infinite loop. Is this because the while-loop needs the values variable to keep repeating itself in it’s scope?
Yes it works perfectly fine, but I’m trying to figure out why is it that if I declare the values variable outside the while-loop and declare it above the while loop scope, why it causes an infinite loop?
I’m wondering is this because the while-loop depends on the values variable to be repeated multiple times?
var max = 10,
lowest = 1,
store = [];
var values = Math.floor(Math.random() * max) + 1;
while(store.length < max) {
if(store.indexOf(values) === -1) {
store.push(values);
}
}
store;
The code example above causes an infinite loop, because the values var declaration (with the value assigned) is outside of the while loop. I’m just trying to figure out why does it causes an infinite loop when the values variable (value assigned to it) is outside of the while loop’s block?
But when the values is inside the while-loop, it doesn’t cause an infinite loop…
For example…
var max = 10,
lowest = 1,
store = [];
while(store.length < max) {
var values = Math.floor(Math.random() * max) + 1;
if(store.indexOf(values) === -1) {
store.push(values);
}
}
store;
You’re setting “values” to a random number. When you set it inside the while loop, then you’re getting a new number for every iteration of the loop. But when you set it outside the loop, then the value of “values” never changes after that. Your “if” statement prevents the same number from being pushed more than once, so if “values” never changes, then you’ll never push more than one number.