[英]JS simple function in function won't work
I wanted to make this 1 function and call it in function 2. 我想做这个1函数,并在函数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? 函数是否可能无法进入另一个函数?
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;
}
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. 变量无法“转义”其作用域(在本例中为它们内部的函数),因此您无法从attackModifier
函数访问d6
。 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. MDN文档中可能有一些关于函数返回如何工作的有用解释。
For you get the d6
variable in the attackModifier
function, you need create this variable outside of d6Roll
function. 你所得到的d6
在变量attackModifier
功能,你需要的之外创建这个变量d6Roll
功能。
Look like: 看起来像:
var d6;
function d6Roll() { ... }
function attackModifier() {...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.