I am trying to make an array, shuffle it, then go through it in order. However, when I shuffle it (START) more than once, it messes up! Also When you get to the last number in the randomized array, it messes up also! please help and thank you!
JS
var minnum = 1;
var maxnum = 104;
function start() {
var nums = [];
while(minnum < maxnum+1){
nums.push(minnum++);
}
function shuffle(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
var randomnum = shuffle(nums);
document.getElementById('txt').innerHTML = randomnum;
localStorage["nums"] = JSON.stringify(randomnum);
localStorage.setItem("current", 0);
}
function Link() {
if (localStorage.getItem("current") === null || localStorage.getItem("nums") === null) {
start();
}
var current = localStorage.getItem("current");
var nums = JSON.parse(localStorage["nums"]);
document.getElementById('txt').innerHTML = nums;
document.getElementById('txt1').innerHTML = nums[current];
current++;
if(current > 103) {
location.reload();
start();
current = 0;
}
localStorage.setItem("current", current);
}
HTML
<body>
<input type="button" onclick="start()" value="Start" />
<span id="txt"></span>
<input type="button" onclick="Link()" value="Next" />
<span id="txt1"></span>
</body>
The error seems to be that
minnumANDmaxnumare declared outside of thestart()function and never initialized to 1 and 104 anymore, hence whenever you hit start the second time the firstwhilewill not push anything tonumsarray becauseminnumis 103 (from the previous cycle) andmaxnum104.Fiddle:
http://jsfiddle.net/1pd18eun/1/
Code (just moved minnum and maxnum inside):
Besides, for the sake of readers and good people, start to indent your code, it was very hard to properly understand what you were doing.