Here is one of the similar example
var global=0;
function somefunction()
{
global++;
}
var temp=global;
function somefunctiontwo()
{
var x=temp;
}
here I am getting x=0 I want x=1
how can I assign newly assigned value of global variable to x
Use an object as global variable; that will be assigned by reference instead of 'by value' as for the simple (number) type:
var global = { value: 0 };
var temp = global;
in function:
global.value++;
now is:
temp.value == 1
temp
and global
refer to two different variables. Assigning to global
will not change the value in temp
.
Simply change var x=temp
to var x=global
. It's not clear why you need an intermediate variable.
var global=0;
var temp;
function somefunction(){
global++;
}
function somefunctiontwo() {
var x=temp;
console.log(x);
}
somefunction();
temp=global;
somefunctiontwo();
This will give what you expect. Pay attention on how/where you call the functions.
Your structure seems a little off, not sure if this is for a reason we can't see... Will presume it is. Can have a function that resyncs the temp value to global.
function syncGlob(){
return temp = global;
}
Returns temp as well so you can call it when creating x.
var x = syncGlob();
You're setting the value of temp to global PRIOR to the on ready firing - at this point global is 0. If you increment global at on ready, temp already has a value of 0.
When you click somefunction2 and assign x the value of temp, temp has a value of 0, because at the time of temp initiation, global had a value of 0 NOT 1
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.