This may not be the best method as it uses recursion, but it works. It gets a random number and adds it to a list of used numbers, making sure not to return a number that is in the array of already used numbers.
There are plenty of ways to do this, this is just one of them.
var usedNumbers = []
var randomNumber = function () {
var range = 10
// If the list of used numbers is the same as the range, we have gone
// through all numbers
if (usedNumbers.length === range) {
console.error('Max numbers reached')
return false
}
var list = []
for (var i = 1; i <= range; i++) {
list.push(i);
}
var random = Math.floor(Math.random(list) * range) + 1
// If the number appears in the list of used numbers, re-run the function
if (usedNumbers.indexOf(random) != -1) {
return randomNumber()
}
// add the number to the list
usedNumbers.push(random)
return random
}
// Get a random number 11 times (last one will return false)
for (var i = 0; i <= 10; i++) {
console.log(randomNumber())
}
Here's another method based on @Wainage comment of creating an array and popping the number off it.
var upperLimit = 10
var range = []
// Add the range of numbers to the array
for (var i = 1; i <= upperLimit; i++) {
range.push(i)
}
var randomNumber = function () {
// pick a random number from the array
var random = range[Math.floor(Math.random() * range.length)]
// remove it from the array
range.splice(range.indexOf(random), 1)
return random
}
// Call a random number 15 times
// If no number, it will return undefined
for(var i = 0; i < 15; i++) {
console.log(randomNumber())
}