我正在尝试制作一个数组,将其洗牌,然后按顺序完成。然而,当我不止一次地将它(START)洗牌时,它会变得混乱!当你到达随机数组中的最后一个数字时,它也会混乱!请帮助,谢谢!
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>
答案 0 :(得分:0)
错误似乎是minnum
和maxnum
在start()
函数之外声明而从未初始化为1和104 ,因此每当您点击开始第二时间,第一个while
不会将任何内容推送到 nums
数组,因为minnum
为103(来自上一个周期) )和maxnum
104。
小提琴:
http://jsfiddle.net/1pd18eun/1/
代码(刚刚移动了minnum和maxnum):
function start()
{
var minnum = 1;
var maxnum = 104;
var nums = [];
while(minnum < maxnum+1){
nums.push(minnum++);
}
var randomnum = shuffle(nums);
document.getElementById('txt').innerHTML = randomnum;
localStorage["nums"] = JSON.stringify(randomnum);
localStorage.setItem("current", 0);
}
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;
}
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);
}
此外,为了读者和好人,开始缩进代码,很难正确理解你在做什么。