Why does the JS loop assignment end up wrong?

var style = { fontsize: 12, left: 0 };
var style_array = new Array();

function tt(){
    ss();
    for(var j=0;j<12;jPP){
        console.error(style_array[j].left + " "+ j+" " + style_array[j].fontsize);
    }
}

function ss(){
for (var i = 0; i < 12; iPP) {
    style.fontsize = parseInt((Math.random() * 1 + 1) * 12);
    style.left = parseInt(300 * Math.random() * 0.8);
    style_array[i] = style;
  }
  console.log(style_array);
}
tt();

the final output is the value of style [12], indicating that only the last one is retained when assigning the value. why?

< hr >

just tested it, and found that as long as you jump out of the for loop in ss (), style_array [] will all become the same value

.
var style = { fontsize: 12, left: 0 };
var style_array = new Array();
function ss(){
for (var i = 0; i < 12; iPP) {
    style.fontsize = parseInt((Math.random() * 1 + 1) * 12);
    style.left = parseInt(300 * Math.random() * 0.8);
    style_array[i] = style;
    if(i>=1) console.log(style_array[i-1]);
  }
  console.log(style_array);
}
ss();
The

problem can be simplified. Why are all the output values the same above?

< hr >

solved

var style = { fontsize: 12, left: 0 };
var style_array = new Array();

function ss(){
for (var i = 0; i < 12; iPP) {
    style={};//*************************
    style.fontsize = parseInt((Math.random() * 1 + 1) * 12);
    style.left = parseInt(300 * Math.random() * 0.8);
    style_array[i] = style;
  }
  console.log(style_array);
}
ss();
Mar.07,2022

style has always been an object, and if it is modified, so will what is saved in the array.
because the data in the array all points to a memory address. Make a deep copy of the object when it is assigned.
var s = JSON.parse (JSON.stringify (style));
modify the value of the s object in the loop to OK

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b43301-2bbbc.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b43301-2bbbc.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?