根据前一个值从数组中选择值

我有数组有我需要的行大小并像这样随机选取


const Numbers = ["8", "4", "6", "2"];

const randomNumber = Numbers[Math.floor(Math.random() * Numbers.length)];

console.log(randomNumber)


这会给我一个来自数组的随机值


现在我要做的是选择 3 个数字,它们的总和是 12,然后它重置并重新开始。


例子:


随机数组选择数字 8 之后数字应该是 4 或数字 2 两次然后重新开始


选择号码 4 所以可用号码应该是 4 两次或 2 四次或 4 一次和 2 两次 ...等等


所以总和应该是 12 然后再次重置


当然,所有这些都将在循环内,但我想知道的是最好的方法。


====更新====


这是使用的 HTML


randomRow 应该有值,每 3 行应该是 12


for (let i = 0; i < results.length; i++) {


    document.getElementById("someID").innerHTML += `


                <div class="col-`+randomRow+`">

<p>Hello</p>

                </div>`


}


芜湖不芜
浏览 88回答 2
2回答

呼唤远方

考虑下面的小游戏,它使用你的情况,它从源数组中计算你的 randomNumber 的总和。它检查总和是否 >= 12。然后让游戏休息!这有帮助吗?const Numbers = [8, 4, 6, 2];var randomNumber = 0;var sum = 0;function calcSum() {&nbsp; randomNumber = Numbers[Math.floor(Math.random() * Numbers.length)];&nbsp; sum = sum + randomNumber;&nbsp; if (sum >= 12) {&nbsp; &nbsp; document.getElementById('calculatedTotal').innerHTML = "Your score exceeded 12, click 'start game' to play again!";&nbsp; &nbsp; sum = 0;&nbsp; &nbsp; randomNumber = 0;&nbsp; }&nbsp; else {&nbsp; &nbsp; document.getElementById('calculatedTotal').innerHTML = sum;&nbsp; }}<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; &nbsp; <title>Document</title></head><body>&nbsp; &nbsp; <button id="btn" onclick="calcSum()">Start game!!</button>&nbsp; &nbsp; <h2>Your Score: </h2>&nbsp; &nbsp; <h3 id="calculatedTotal"></h3>&nbsp; &nbsp; <script src="test.js"></script></body></html>

青春有我

每次选择随机数时您必须过滤掉不构成 12 的数字。从总和中减去选择的数字,然后重复步骤 1 直到总和达到 0编辑:根据问题更新,假设您使用的是 Bootstrapdocument.getElementById("start").addEventListener("click", _ => {&nbsp; let sum = +document.getElementById("sum").value;&nbsp; let numbers = document.getElementById("numbers").value.split(',').map(x=>+x);&nbsp; let picked = [];&nbsp;&nbsp;&nbsp; while(sum > 0) {&nbsp; &nbsp; // filter available `numbers` based on the `sum`&nbsp; &nbsp; numbers = numbers.filter(x => x <= sum);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; let n = numbers[Math.floor(Math.random() * numbers.length)];&nbsp; &nbsp; picked.push(n);&nbsp; &nbsp; // subtract `n` from `sum`&nbsp; &nbsp; sum -= n;&nbsp; }&nbsp;&nbsp;&nbsp; document.getElementById("row").innerHTML = picked.map(n => `<div class="border border-dark p-3 col-${n}">col-${n}</div>`).join("");&nbsp;&nbsp;});<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>Sum: <input type="text" id="sum" value="12" />&nbsp;Numbers: <input type="text" id="numbers" value="8,6,2,4" /> <br/><button type="button" id="start">Start</button><div class="container-fluid">&nbsp; <div class="row" id="row">&nbsp; &nbsp;&nbsp;&nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript