+ 2

Funcion and Variable related Question

Hi everyone. So, on my script, I have a function that is called once you click a button. It adds 1 to a variable. The problem is that I can't use the total value later in the script. I would like to use that value on another function. Is that possible?? Thank you all

2nd Jul 2020, 2:12 PM
Alexandre
Alexandre - avatar
10 Respostas
+ 1
Alexandre Now I see the problem. In your code: var n_jogadores, inputPlayers, nomear, jogador=new Array(11), jog=new Array(11), p; function maisJogadores(){ n_jogadores++; } the variable n_jogadores has no value (NaN) and you want to add the 1. This does not work in most of the programming languages.
2nd Jul 2020, 5:40 PM
JaScript
JaScript - avatar
+ 5
You can do that by making that variable global scope.
2nd Jul 2020, 2:23 PM
Raj Chhatrala
Raj Chhatrala - avatar
+ 2
Yes of course, that is possible. Where is your attempt or better a link to it?
2nd Jul 2020, 2:19 PM
JaScript
JaScript - avatar
+ 2
This is the code, I took a few parts off, cause I needed all html pages for this to work. https://code.sololearn.com/W28WXUSbgwGk/?ref=app
2nd Jul 2020, 2:33 PM
Alexandre
Alexandre - avatar
+ 2
🔫 Rick Grimes What is that? And how can I do it??
2nd Jul 2020, 2:34 PM
Alexandre
Alexandre - avatar
+ 2
Thanks Ja Play But, on my code, I declare the variable "n_jogadores=0" at the beginning. Then, at the function I add 1, now "n_jogadores" should be equal to 1. And when I use "alert(n_jogadores)" inside of the function, it says "1" but outside doesn't. Well, I came up with the idea of using "sessionStorage" for this. I think it will work, but if you don't mind, why does it(what I said earlier) happen? Anyway, thanks for your time
2nd Jul 2020, 4:03 PM
Alexandre
Alexandre - avatar
+ 2
Ja Play I see. Ok, I'll try to use it and then I'll set your answer as correct. Btw, sorry about the name of my variables. English isn't my mother language. Thank you all : ) [Edit] I've already test it and it works, so @Ja Play Thanks a lot. Your answer saved me hours of searching!
2nd Jul 2020, 6:05 PM
Alexandre
Alexandre - avatar
+ 1
Maybe that can be helped: In the example below, a is a global variable and b is local variable. // a can here be used but b cannot be here used var a = 4; function myFunction() { // a and b can here be used var b = 3; return a * b; } // b cannot be here used. a can here be used. https://www.sololearn.com/learn/315/
2nd Jul 2020, 3:23 PM
JaScript
JaScript - avatar
+ 1
Alexandre it‘s works. Try the code below: var counter = 0; function first() { counter++; } function second(){ alert(counter); } first(); second(); console.log(counter); counter++; second();
2nd Jul 2020, 5:31 PM
JaScript
JaScript - avatar
+ 1
Your welcome Alexandre . The idea - if you want to change the page - using session storage for onward transmission is good.
2nd Jul 2020, 8:49 PM
JaScript
JaScript - avatar