In response to abc’s answer, I’m not sure how the random() method would help me accomplish this task?
? Favorite Answer
Use Math.random() to generate a random number.
“Returns a floating-point, pseudo-random number in the range [, ) that is, from (inclusive) up to but not including (exclusive), which you can then scale to your desired range.”
Combined with Math.floor and the length of your array, you can generate a random integer between and including and the last index number of your array. So something like:
var randomIndex = Math.floor(Math.random() * text.length)
Then you can create an if statement. If your <p> tag is empty then assign it the the text from your array element at randomIndex.
If you want the text to be different each time then add an else to your if statement. Make a loop that runs while the innerHTML property of your <p> tag is equal to the text array element at randomIndex. In the body of the loop, generate a new random number. The loop will automatically stop when the innerHTML of your <p> tag and the text in the your array at randomIndex don’t match.
Then the program can assign the text from the array at randomIndex to the innerHTML property of your paragraph.
Here’s an example.
how would I make it so that the button would change the text to something different every time I click it?
random number can be used to retrieve a string at random index position of array of strings
Would I be able to create an array and use a for loop to return a different length each time?
Is there some way to break the script after the first click?
– don’t know