简体   繁体   English

随机生成的数组中的最大数量

[英]The max number in a randomly generated array

So this is what I have so far:所以这就是我到目前为止所拥有的:

 function pirmaUzduotis() { var answer = []; var c = 0; answer[c] = Math.floor(Math.random() * 76) - 35; document.getElementById("answer").innerHTML = answer; }
 <button onclick="pirmaUzduotis()">Click me</button> <p id="answer"></p>

 function antraUzduotis() { var answer2 = []; var a = 0; var b = 0; for (b = 0; b < 20; b++) { a = Math.floor(Math.random() * 76) - 35; answer2[b] = a; } document.getElementById("answer2").innerHTML = answer2; }
 <button onclick="antraUzduotis()">Click me</button> <p id="answer2"></p>

So the first one is just an extra, the main focus is, the randomly generated array.所以第一个只是一个额外的,主要关注的是随机生成的数组。 I wish to create a button that on click shows me the highest number in the array.我希望创建一个按钮,单击时会显示数组中的最高数字。 I mainly attempting to use Math.max .我主要尝试使用Math.max Here's what I have so far:这是我到目前为止所拥有的:

 function treciaUzuotis() { var array = arr; var array = answer3 var max = Math.max.apply(null, arr); } document.getElementById("answer3").innerHTML = answer3
 <button onclick="treciaUzduotis()">Click me</button> <p id="answer3"></p>

I believe my biggest problem is identifying the array as a variable.我相信我最大的问题是将数组识别为变量。 Any help would be much appreciated, thank you.任何帮助将不胜感激,谢谢。

Just return the value of array from antraUzduotis只需从 antraUzduotis 返回数组的值

JS Code JS代码

<script>
    function antraUzduotis() {
        var answer2 = [];
        var a = 0;
        var b = 0;
        for (b = 0; b < 20; b++) {
            a = Math.floor(Math.random() * 76) - 35;
            answer2[b] = a;
        }
        return answer2;

    }
    function treciaUzduotis() {
        document.getElementById("answer3").innerHTML = Math.max.apply(null, antraUzduotis());
    }
</script>

Html Code html代码

  <button onclick="treciaUzduotis()">Click me</button>
  <p id="answer3"></p>

Store you array of random numbers globally, you will access it later in with the findMax function.全局存储随机数数组,稍后您将使用findMax函数访问它。

You can use the spread operator with the Math.max to pass all the random number at the function.您可以在Math.max 中使用扩展运算符来传递函数中的所有随机数。

 var answer2 = []; // store the array globaly // fill it up with random values function antraUzduotis() { var a = 0; var b = 0; for (b = 0; b < 20; b++) { a = Math.floor(Math.random() * 76) - 35; answer2[b] = a; } document.getElementById("answer2").innerHTML = answer2; } // then you can access it in another function function findMax() { document.getElementById("max").innerHTML = Math.max(...answer2); }
 <button onclick="antraUzduotis()">Generate Random</button> <button onclick="findMax()">Find Max</button> <div> Randoms : <span id="answer2"></span></div> <div> Max : <span id="max"></span></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM