Js closure problem

the following is a simple for loop, and the resulting output is all Xero4;

var a=[];
for(var i=0;i<5;iPP){ 
 var b={};
  b.x=i;
  a[i]=b;  
}
console.log(a);

sources of topics and their own ideas

related codes

/ / Please paste the code text below (do not replace the code with pictures)

what result do you expect? What is the error message actually seen?

Apr.16,2021

is not caused by closures, but because b is an object and a variable of reference type . When you put the value of b into an array, it is actually only a memory address, not the value of b itself. Every time you change the value of b in the loop, it will also change the value of b that has been added to the array a, so the value of an in the end, the b in it is all the same. Think of your expected result, as you said later, to redeclare a b in the body of the loop.
by the way, loops do not produce closures, which only exist in the body of the function.


does this have nothing to do with closures? In the first example of
,
first assigns a value to the x property of object b, and subsequent loops just modify the x property, which ends up with an x attribute of 4, but the b object always has only one instance object.
and a [I] = b; just point each value in array a to an instance of array b.

Menu