猿问

如何在随机生成的数字上添加函数

是否可以在随机生成的数字上添加函数。例如,我使用getRndInteger(min, max),Math.floor()和Math.random()生成随机数,并在这些数字中添加函数以查看生成的数字中哪个最大。我在想也许可以将每个随机数放在数组中并Math.max()在它们上使用,但我不太确定您如何将这些数字放入一个函数中,例如单击时,您会看到生成的数字和结果(最大的它们的数量)在它下面。我主要想知道它是否可能,如果可能,如何。我会非常感谢!


所以我特别想使用一个从 -35 到 76 的随机数,包括 -35 和 76。我做了一个按钮,点击后会显示随机数。对我来说另一个问题是,我不知道如何一个接一个地添加一个随机数,而不是点击添加一个新的。(哈哈对不起,如果这是一个超级新手问题)。然后我在显示答案的段落上放了一个 id。我正在考虑使用document.getElementById("")forMath.max.apply()并使用另一个显示答案的 ID 制作另一个段落。


<button onclick="document.getElementById('result').innerHTML = getRndInteger(-35,76)">Click Me</button>


Chosen number:

<p id="result"></p>


Biggest number:

<p id="result2"> </p>


<script>

    function getRndInteger(min, max) {

        return Math.floor(Math.random() * (max - min)) + min;

    }


</script>


<script>

       Array.max = function(document.getElementById("result");) {

        return Math.max.apply(document.getElementById"result");

    };


</script>

当我作为数组放入.getElementById()时Math.max.apply(),即使点击,java 脚本也不再加载随机数。也许您必须在答案中添加 id 或其他内容,我在这里完全没有想法。任何帮助将不胜感激!我也想我是否仍然使用Math.max()这样做并避免任何过于复杂的代码来理解问题并在未来的代码中使用答案。谢谢你!


qq_笑_17
浏览 228回答 1
1回答

阿晨1998

您应该存储之前生成的最大数字,以便能够确定当前生成的数字高于它。请参阅片段以获得一个想法。(() => {&nbsp; let max = null;&nbsp; const range = {&nbsp; &nbsp; min: -35,&nbsp; &nbsp; max: 76&nbsp; };&nbsp; const result = document.querySelector("#result");&nbsp; const maxResult = document.querySelector("#resultMax");&nbsp; const allNrs = document.querySelector("p#all");&nbsp; document.querySelector("button").addEventListener("click", handleButtonClick);&nbsp; function handleButtonClick() {&nbsp; &nbsp; const someRandomNumber = getRndInteger(range.min, range.max);&nbsp; &nbsp; result.textContent = someRandomNumber;&nbsp; &nbsp; max = max && someRandomNumber > max&nbsp;&nbsp; &nbsp; &nbsp; ? someRandomNumber&nbsp;&nbsp; &nbsp; &nbsp; : max&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; ? max&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; : someRandomNumber;&nbsp; &nbsp; maxResult.textContent = max;&nbsp; &nbsp; allNrs.textContent += ` ${someRandomNumber} `;&nbsp; }&nbsp; function getRndInteger(min, max) {&nbsp; &nbsp; return Math.floor(Math.random() * (max - min)) + min;&nbsp; }})();#all {&nbsp; max-width: 400px}<p>&nbsp; <button>Click Me</button></p>Random number:<span id="result"></span><br>Biggest number until now:<span id="resultMax"></span><div>&nbsp; <br>All numbers until now:&nbsp; <p id="all"></p></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答