JS function with loop in a loop iterator problem
This is my code:
function func(){
 for(i=0; i < 5; i++){
   alert('B');
 }
}
for(i=0; i开发者_运维百科 < 5; i++){
  func();
  alert('A');
}
What I expected was: BBBBBABBBBBABBBBBABBBBBABBBBBA
but what received was just BBBBBA
I found out that's because there is function scope, not block scope in JS. What I'd like to know is how to preserve such a behavior. I mean to force something like block scope. Otherwise it's very easy to make really nasty bugs - e.g. while using a function somebody else wrote or the one you wrote yourself, but a few months earlier.
Make sure you use var i=0 instead of just i=0.  Otherwise, it floats into the global scope and gets used by both loops.
function func(){
    for(var i=0; i < 5; i++){
       alert('B');
    }
}
for(var i=0; i < 5; i++){
    func();
    alert('A');
}
The problem is with i being global variable. User var to confine its scope to func function:
function func(){
  for(var i=0; i < 5; i++){
    alert('B');
  }
}
Functions with variables declared that way will not pollute the global namespace.
Set the variable i to local scope in the function func
function func(){
 for(var i=0; i < 5; i++){
   alert('B');
 }
}
Don't use global variables (which as you noticed, can be accidently changed by all code. That isn't anything to do with lexical scoping, that would happen in C as well with similar code). Instead make each variable local:
function func(){
 for(var i=0; i < 5; i++){ // var
   alert('B');
 }
}
for(var i=0; i < 5; i++){ // var
  func();
  alert('A');
}
function func(){
 for(var i=0; i < 5; i++){
   console.log('B');
 }
}
for(var i=0; i < 5; i++){
  func();
  console.log('A');
}
this should work for you
http://jsfiddle.net/jvXHM/
Use var to make i local:
function func(){
 for(var i=0; i < 5; i++){
   alert('B');
 }
}
for(i=0; i < 5; i++){
  func();
  alert('A');
}
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论