开发者

a problem occur when push a object into a array

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}, Objec开发者_StackOverflow社区t { id=3}, Object { id=3}]


The problem is that you're reusing the same object on all of the loop iterations. Create a new entry object within the 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 one here, with `id` prop)
   test.push(entry);
}

console.log(test);

Otherwise, if you just assign to entry.id on each loop, you're just changing the id property 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 entry variable entirely if you like, but you may want to keep it for 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 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.:

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

is the same as

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

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:

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

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.


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

console.log(test);

Try that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜