To simplify, I have an array that I would like to randomize by clicking a button
. Once randomized, I want to display the first result from the array with another button
. The array is currently randomized when opened in Chrome, and checking the results in the inspection window shows that the randomization is working with the button.
However, there is another button
for printing the first result on the screen. Currently, it prints in a separate window, which is an issue to address later.
In essence, the randomize button seems functional in the inspection window but not when attempting to use the print button.
Here is my code :
const magicitems = [];
magicitems[0] = "hammer ";
magicitems[1] = "gaunlet ";
magicitems[2] = "cloak ";
magicitems[3] = "chalk ";
magicitems[4] = "- ";
//shuffling the array with a command, is specific?//// i have no real idea what this bit means//
const Shuffle = magicitems => {
for (let i = magicitems.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = magicitems[i];
magicitems[i] = magicitems[j];
magicitems[j] = temp;
}
return magicitems
};
Shuffle(magicitems); //shuffling magic items//
var RandomItem = magicitems[0]; //making a var that is 1 item from magicitems//
const print = document.getElementById("demo").innerHTML = magicitems;
//printing the array was the first thing i did before the shuffle, now i shuffle first and am trying to print RandomItem to get 1 random item from the array//
// it worked, now i am trying to make a button that will do document.getElementById("demo").innerHTML = RandomItem; on a click instead of command
//after i made the button, the const print was no longer needed to put the result on the screen
<h2>random magic item</h2>
<p id="demo"></p>
<button type="button" onclick="Shuffle (magicitems)">random</button>
<button type="button" onclick="document.write(RandomItem)">print</button>
The array actually has 165 items so I reduced that for readability purposes. The concept remains the same - shuffling the array when clicking random and displaying the result in the same window upon pressing print.