Reputation: 27
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
. 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.
Upvotes: 1
Views: 53
Reputation: 2348
Just return the value of array from antraUzduotis
JS Code
<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
<button onclick="treciaUzduotis()">Click me</button>
<p id="answer3"></p>
Upvotes: 2
Reputation: 1570
Store you array of random numbers globally, you will access it later in with the findMax
function.
You can use the spread operator with the Math.max to pass all the random number at the function.
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>
Upvotes: 0