3 回答

TA贡献1830条经验 获得超3个赞
这是关于洗牌列表。您应该首先创建一个元素数组(不将它们附加到父元素),将其洗牌,然后parent.append(...list)
.
您可以在此处了解如何打乱列表: How to randomize (shuffle) a JavaScript array?

TA贡献1876条经验 获得超6个赞
您可以提出一系列挑战并使用自定义比较器对该数组进行排序:
challenges = [
num1*num2,
num1*2+Math.floor(Math.random() *3) + 1,
num1*num2+Math.floor(Math.random() *9) + 1,
num2+Math.floor(Math.random() *9) + 1
]
function randomizer () { return Math.random() > 0.5 }
challenges.sort(randomizer)
for (challenge of challenges) makeButton(challenge)
编辑 为了获得更好的随机化效果,您可以制作一个具有随机索引的对象列表并对其进行正常排序:
challenges = [
{ challenge: num1*num2, index: Math.random() },
{ challenge: num1*2+Math.floor(Math.random() *3) + 1, index: Math.random() },
{ challenge: num1*num2+Math.floor(Math.random() *9) + 1, index: Math.random() },
{ challenge: num2+Math.floor(Math.random() *9) + 1, index: Math.random() }
]
function compare(a,b) { return a.index == b.index ? 0 : a.index > b.index ? 1 : -1 }
challenges.sort(compare)
for (i in challenges) makeButton(challenges[i].challenge)

TA贡献1865条经验 获得超7个赞
将“挑战”放入一个数组中并对其进行洗牌。您可以按照此答案中所述在普通 javascript 中随机播放,但我更喜欢使用rando.js 随机播放,如下所示:
console.log( randoSequence(["a", "b", "c"]) );
<script src="https://randojs.com/2.0.0.js"></script>
将该洗牌应用到您的按钮,您将拥有:
var num1 = 2;
var num2 = 4;
var btncount = 0;
challenge1 = num1 * num2;
challenge2 = num1 * 2 + Math.floor(Math.random() * 3) + 1;;
challenge3 = num1 * num2 + Math.floor(Math.random() * 9) + 1;
challenge4 = num2 + Math.floor(Math.random() * 9) + 1;
//------------CHANGED PART------------
var shuffledChallenges = randoSequence([challenge1, challenge2, challenge3, challenge4]);
makeButton(shuffledChallenges[0].value);
makeButton(shuffledChallenges[1].value);
makeButton(shuffledChallenges[2].value);
makeButton(shuffledChallenges[3].value);
//--------END OF CHANGED PART.--------
function makeButton(number) {
btncount = btncount + 1;
/* create a button */
var b = document.createElement('button');
b.setAttribute('class', 'pure-button');
b.setAttribute('onclick', `check(${number})`);
b.setAttribute('id', btncount);
b.textContent = number;
var buttons = document.getElementById("buttons");
buttons.appendChild(b);
}
<script src="https://randojs.com/2.0.0.js"></script>
<div id='buttons' class="pure-button-group" role="group"></div>
添加回答
举报