Trivial question. What I have so far http://jsfiddle.net/Dth2y/1/
Task, the next button should randomly select a value from the array and remove that value from the array. So far this called the getNames function, within this function the value randomly selected from the array should be removed too after being appended to the html.
HTML
<h1 id="name">Click Next To Start</h1> <button id="next">NEXT NAME</button> <button>SKIP NAME</button>
JS
$(document).ready(function() {
var names = [
"Paul",
"Louise",
"Adam",
"Lewis",
"Rachel"
];
function getNames() {
return names[Math.floor(Math.random() * names.length)];
}
$("#next").click(function() {
$('#name').text(getNames())
});
});
I have seen similar questions using the splice method, I have tried to hack a version together but am wondering if there's a more efficient way.
You could instead randomly shuffle the array before-hand and then
pop()
the first element orshift()
the last element.(The
shuffle
function is based on the Fisher-Yates shuffle algoritm. This post explains how it works.)you will want to check this out: http://ejohn.org/blog/javascript-array-remove/
here it is applied to your fiddle: http://jsfiddle.net/Dth2y/3/