0

Is it possible to choose a variable in an array only once? I have made a click function where it gives me a random quote every time i click. How do I make it so that it won't pick the same variable again?

What I want to be able to do is click the button as many times as I want to without running into the same quote again as long as there are more "unseen" quotes. (I didn't include all the original quotes in the code snippets).

var quotes = [
	'Catsy',
	'Jope',
	'Nope',
	'Hey',

]

function newQuote() {
	var randomNumber = Math.floor(Math.random()*(quotes.length));
	document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
}
html { 
  background: url(bild.jpg) 
  no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
h1 {
	text-align: center;
	color: rgb(77, 77, 77);
	font-size: 120px;
	font-family: "Courier New", monospace;
}
div {
	color: white;
	text-align: center;
	font-family: "Courier New", monospace;
	justify-content: center;
	font-size: 45px;
	margin-right: 400px;
    margin-left: 400px;
}
button {
	height:30px; 
    width:150px; 
    margin: 300px -100px; 
    position: absolute;
    top:50%; 
    left:50%;
    font-size: 16px;
    font-family: "Courier New", monospace;
}
<!DOCTYPE html>
<html>
<head>
	<title>Bop</title>
	<link rel="stylesheet" type="text/css" href="fp.css">
</head>

<body>
	<h1>Mjao</h1>

	<div id="quoteDisplay">
		
	</div>
	
		<button onclick="newQuote()">Another one!</button>
	

	<script src="fp.js"></script>
	
</body>

</html>	

1
  • The easiest way is to randomize your quotes array, then loop from the start, when you get to the end, randomize your quotes array, rinse and repeat. Commented Apr 16, 2018 at 15:45

4 Answers 4

1

An easy way to do this is to shuffle a copy of the array, and then just iterate through it. See this answer for how to shuffle it:

How to randomize (shuffle) a JavaScript array?

Sign up to request clarification or add additional context in comments.

Comments

0

I think what you want is to simply remove the quote from the array after showing it.. so something like this should work:

quotes.splice(randomNumber, 1);

if you add it to newQuote() at the bottom...

Comments

0

or you just push the used words in an seprate array and check with

usedWordsArray.includes('Catsy')

Comments

0

just remove the item from the array when you're done with it.

    quotes.splice(randomNumber, 1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.