In JavaScript, I would like to randomly remove an item from an array and display this within the HTML on a button click. Then on the next click of the button show the next removed item from the array. However, this doesn't seem to be working!
The fiddle: http://jsfiddle.net/bs4e5g69/
document.getElementById("Button").onclick = function() {
var count = 3;
var myArray = [
'A',
'B',
'C',
'D',
'E',
'F',
'G'
];
var tmpArrayE = myArray.slice(myArray);
var goE = [];
for (var i = 0; i < count; i++) {
var optionsE = Math.floor(Math.random() * tmpArrayE.length);
var removedE = tmpArrayE.splice(optionsE, 1);
goE.push(removedE[0]);
}
document.getElementById("Answer").innerHTML = goE[0];
}
You are redefining your array in your event handler, so your array will never be empty !
Here is your updated code :
// myArray initial content, as a global variable :
var myArray = [
'A',
'B',
'C',
'D',
'E',
'F',
'G'
];
// the event handler, randomly emptying myArray one at a time :
document.getElementById("Button").onclick = function() {
// check for an empty array :
if (myArray.length > 0) {
var optionsE = Math.floor(Math.random() * myArray.length);
var removedE = myArray.splice(optionsE, 1);
document.getElementById("Answer").innerHTML = removedE[0];
} else {
alert("the array is now empty");
}
}
You are declaring myArray
inside onclick function. So on every click it will create an new array.
var myArray = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G' ]; document.getElementById("Button").onclick = function() { //check if myArray length is greater than 0 if (myArray.length > 0) { // generate random number var optionsE = Math.floor(Math.random() * myArray.length); // remove that element & show in div var removedE = myArray.splice(optionsE, 1); document.getElementById("Answer").innerHTML = removedE; } }
<button id="Button"> Start </button> <div id="Answer"> Result </div>
If you like to use a copy of myArray
, you need to move this line outside of the callback, because you get always a (new) copy for every event.
var tmpArrayE = myArray.slice(0); // myArray.slice(myArray) is wrong.
For using the original array in the callback, you could just use myArray
.
Plan A: Start by shuffling the array. Then pop the last element off when one is needed.
Plan B: Pick a random element from 0 to len-1. Copy the last element into that slot. Then shorten the array by one.
If you need a "shuffle" function, do this (only N steps; result is random):
for j = 0..N-1
swap item #j with item # rand(0..N-1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.