javascript - a problem occur when push a object into a array -


here's 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 array 3 different object. objects same, why?

[object { id=3}, object { id=3}, object { id=3}]

the problem you're reusing same object on of loop iterations. create new entry object within loop:

var arr = [1,2,3]; var entry;                      // (modified, don't create here) var test = []; for(var i=0;i<arr.length;i++){    entry = {id: arr[i]};        // (modified, create new 1 here, `id` prop)    test.push(entry); }  console.log(test); 

otherwise, if assign entry.id on each loop, you're changing id property on same object. when push object reference onto array, you're pushing reference, not copying object.

you can, of course, away entry variable entirely if like, may want keep clarity, etc. here's without:

var arr = [1,2,3]; var test = []; for(var i=0;i<arr.length;i++){    test.push({id: arr[i]}); }  console.log(test); 

somewhat off-topic:

that structure creating object , simultaneously assigning properties called object literal. if had multiple properties, you'd separate initializers commas. e.g.:

var obj = {a: 1, b: 2, c: 3}; 

is same as

var obj = {}; obj.a = 1; obj.b = 2; obj.c = 3; 

the values (the right-hand side of :) can expressions in assignment statement. names (the left-hand side of :) either literals, above, or strings:

var obj = {"a": 1, 'b': 2, c: 3}; //         ^^^     ^^^     ^---- literal fine //          |       +----------- string (with single quotes) fine //          +------------------- string (with double quotes) fine 

off-topic side note: if @ point find using json data exchange, rules similar more restrictive (json subset of object literal notation). specifically, property names must in double quotes, , string values (even on right-hand side) must in double quotes.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -