I wanted to make this 1 function and call it in function 2.
function d6Roll(){
var d6 = 1 + Math.floor(Math.random() * 6);
}
function attackModifier(){
d6Roll();
var aMod = d6;
document.getElementById("rezultatD6").innerHTML = aMod;
}
For some reason it works only like this:
function d6Roll(){
var d6 = 1 + Math.floor(Math.random() * 6);
document.getElementById("rezultatD6").innerHTML = d6;
}
Is it possible that function can't go inside another function?
-
Problem solved, sorry for bothering you people with basics i obviously missed >.<Martin Markovic– Martin Markovic2016年07月30日 12:35:34 +00:00Commented Jul 30, 2016 at 12:35
3 Answers 3
I think you want to change the first function to this
function d6Roll(){
return 1 + Math.floor(Math.random() * 6);
}
so that you can call it in the second function like this
function attackModifier(){
var aMod = d6Roll();
document.getElementById("rezultatD6").innerHTML = aMod;
}
Comments
is it possible that function cant go in another function?
It is completely possible, you're just doing it incorrectly. Variables can't 'escape' their scope (in this case, the function that they're inside), so you can't access d6 from the attackModifier function. Instead, return the value, like so:
function d6Roll(){
return 1 + Math.floor(Math.random() * 6);
}
You can then get the value of the roll like this:
function attackModifier(){
var aMod = d6Roll();
document.getElementById("rezultatD6").innerHTML = aMod;
}
The MDN documentation might have some useful explanation about how function returns work.
Comments
For you get the d6 variable in the attackModifier function, you need create this variable outside of d6Roll function.
Look like:
var d6;
function d6Roll() { ... }
function attackModifier() {...}