If i have a function that have certain variable in it for example
var test = 3;
function looper(){
var testing = 1;
testing += testing;
}
for (var i=0;i<=10,i++){
looper();
alert(test);
}
if this function is been called in a loop each will get testing value as 2 or it is updating to last executed value ? beside can i get the value of test variable passed into the function or need to pass it as parameter ?
beside can i get the value of test variable passed into the function or need to pass it as parameter ?
Yes, try
var test = 3;
function looper(testing)
{
testing += testing;
return testing;
}
for (var i=0;i<=10,i++)
{
test = looper(test);
alert(test);
}
You have var testing = 1;
so even if looped will be always over and over firstly instantiated to 1
.
You should move it outside of the function scope:
var testing = 3; // NOT "test" but "testing"!!!!!
function looper(){
testing += testing;
}
for (var i=0;i<=10,i++){
looper();
}
alert(testing); // "testing", remember?
The variable test is globally declared so the value 3 is displayed on alert. Where as on every call to a function looper the variable testing is created without retaining previous value and assigned a value 1 in that way the value of testing is always 2 on function call.
var test = 3;
var testing = 1;
function looper(){
testing += testing;
return testing;
}
for (var i=0;i<=10,i++){
test = looper();
alert(test);
}
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.