here’s the code
var arr = [1,2,3];
var entry = {};
var test = [];
for(var i=0;i<arr.length;i++){
entry.id = arr[i];
test.push(entry);
}
console.log(test);
i wanna output a array with three different object. but now my objects are all the same, why?
[Object { id=3}, Object { id=3}, Object { id=3}]
The problem is that you’re reusing the same object on all of the loop iterations. Create a new
entryobject within the loop:Otherwise, if you just assign to
entry.idon each loop, you’re just changing theidproperty on the same object. When you push an object reference onto an array, you’re just pushing a reference, not copying the object.You can, of course, do away with the
entryvariable entirely if you like, but you may want to keep it for clarity, etc. Here’s without:Somewhat off-topic:
That structure creating an object and simultaneously assigning properties to it is called an object literal. If you had multiple properties, you’d separate their initializers with commas. E.g.:
is the same as
The values (the right-hand side of the
:) can be expressions just as in an assignment statement. The names (the left-hand side of the:) are either literals, as above, or strings:Off-topic side note: If at some point you find yourself using JSON for data exchange, the rules are similar but slightly more restrictive (JSON is a subset of object literal notation). Specifically, property names must be in double quotes, and all string values (even on the right-hand side) must also be in double quotes.