简体   繁体   中英

JS simple function in function won't work

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?

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. 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.

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() {...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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