简体   繁体   中英

JavaScript Loop returns unexpected result

Can anyone tell me why this logs 11 , instead of 9 ?

function foo() {
  function bar(a) {         
    i =3;
    console.log( a + i );     
  } 

  for (var i=0; i<10; i++) { 
    bar( i *2 ); 
    //I know, infinite loop
  } 
} 

foo();

If i is hard-coded in bar(){} , shouldn't the logged result be 9?

This is part of a Scope class and I am lost.

Thanks.

In the first iteration, i is 0 which is smaller than 10 . 0 ( 2 * i ) is passed as a to bar . i gets set to 3 , then the sum is 3 .

In the next iteration, i is incremented to 4 (which is still smaller than 10 ), then 8 ( 2 * i ) is passed as a to bar . i gets reset to 3 , then the sum is 11 .

The next iteration is the same, i is incremented from 3 to 4 again and so on.

Your misunderstanding seems to be that the value of a doesn't change because i gets changed, the multiplication is evaluated first. Or you just missed the i++ statement in the loop header.

@Bergi has the right answer, I just want to expand on it a bit. For primitive types like a string or number the parameter is passed by value. Here you are passing i into bar as the value a. Any changes to i or a will not effect the other's value. This also will not give you an infinite loop as the values for i in this case are [0, 4,5,6,7,8,9]

Now if i had been wrapped inside of an object that was passed to foo then you would have the problem you are asking about. Objects passed to javascript functions are passed by reference, so changes to the object in bar also happen in foo.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM