I was working with javascript and found myself in weird situation. I banged my head several minutes to resolve the issue which would have resolved in a second.
Try to follow below steps:
Create one html page and call this javascript
function fnCall(){
for(x = 0; x < 10; x++){
fnCall1();
alert(x);
}
}
function fnCall1(){
for(x = 0; x < 10; x++){
//your code
}
}
If you go through below snippet of code you must be wondering why alert is coming only once, when it is expected to come 10 times
function fnCall(){
for(x = 0; x < 10; x++){
fnCall1();
alert(x);
}
}
function fnCall1(){
for(x = 0; x < 10; x++){
//your code
}
Above behavior is normal because x is global. If the variable doesn’t have var javascript treats it as a global variable.
Since the x doesn’t have var the variable is global. When fnCall1 is called, loop increments that value of x to 10 making fnCall to run only once.
To resolve the issue, put var in front of x
for(var x = 0; x < 10; x++)
Friday, May 30, 2008
Subscribe to:
Post Comments (Atom)
1 comment:
You guys experiment a lot with the coding. The code given in this post is very simple and easy. I will try to execute it and see the result then I'll tell you its fun or not. This is exellent work.Thanks for this information. Keep it up.
Post a Comment