Push object in Javascript

一世执手 提交于 2020-12-26 04:05:40

问题


I need to push object to array in Javascript, but every time push overwrite the same object I have had already added. For example:

//This is object list
var NewIssue = {};
//This is array
var newIssueList = [];

function myFunction() {
    for (var i = 0; i < 3; i++) {
        NewIssue.Id = i;
        NewIssue.Number = 233 + i;
        NewIssue.Name = "Test" + i.toString();

        newIssueList.push(NewIssue);
    }
}

In the end I will have newIssueList with 3 same objects. Why it does overwrite the first and how to solve this problem?


回答1:


You have to move the object inside the loop.

var newIssueList = [];

function myFunction() {
    for (var i = 0; i < 3; i++) {
        var NewIssue = {};
        NewIssue.Id = i;
        NewIssue.Number = 233 + i;
        NewIssue.Name = "Test" + i.toString();

        newIssueList.push(NewIssue);
    }
}

myFunction();

console.log(newIssueList);

And then you could just extend the object literal a but to make it much more readable:

    for (var i = 0; i < 3; i++) {
        var NewIssue = {
           Id:i,
           Number:233+i,
           Name:"Test"+i
        };

        newIssueList.push(NewIssue);
    }



回答2:


You can also avoid using a superfluous var by creating an inline object:

newIssueList.push({
    Id: i,
    Number: 233 + i,
    Name: "Test" + i.toString()
});



回答3:


There is only one object, and each time you push it into the array, you push a reference to the existing object. When you change the object, every element in the array reflects this, as they all point to the same object.

You need to create a new object on every iteration.

//This is array
var newIssueList = [];

function myFunction() {
  for (var i = 0; i < 3; i++) {
    newIssueList.push({
      id: i,
      number: 233 + i,
      name: "Test" + i.toString()
    });
  }
}

myFunction();

console.log(newIssueList);


来源:https://stackoverflow.com/questions/45256872/push-object-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!