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();