I want to create a function that generates random Integers from a certain interval and each time it is called, it should produce a unique one. For that I have created this generateUniqueInt.
function generateUniqueInt() {
var res = Math.floor(Math.random() * 100);
while (generateUniqueInt.used.indexOf(res) !== -1)
res = Math.floor(Math.random() * 100);
generateUniqueInt.used.push(res);
return res;
}
generateUniqueInt.used = new Array;
for (let i = 0; i < 20; i++) {
console.log(generateUniqueInt());
}
generateUniqueInt.used.sort();
console.log(generateUniqueInt.used);
I called this function few times like this and it works.
Then I wanted to check which values were actually generated and for easier inspection I sorted the used property. But as it seems, used is not an array anymore.
I have tried using generateUniqueInt.used = []; as well as Object.defineProperty but the outcome is the same each time. What am I missing here? Is there a way to create used as an array?
generateUniqueInt.usedwas an array with 20 valuessort()sorts alphanumerically by default,ab > aatherefore12 > 112. If you want to sort numerically:.sort((a,b) => a - b)