在循环中将对象添加到外部数组的Javascript方法

3

我正在尝试将动态创建的Javascript对象添加到一个数组中。我可以遍历DOM并创建对象。但是在显示最终的对象数组时,计数是正确的,但所有对象都具有相同的值,即最终索引值。如何解决这个问题?

PS:DOM遍历和其他功能工作正常,唯一的问题是创建具有正确值的最终对象数组。

Javascript代码。

var match = {};

var matches = [];

$('.SIsort').each(function (i, v) {
      console.log("type.."+typeof matches);
      var date = $(this).find('td:eq(0)').find('meta')[0].content;
      var team1 = $(this).find('td:eq(1)').find('div:eq(1)').text();
      var team2 = $(this).find('td:eq(1)').find('div:eq(3)').text();
      var loc = $(this).find('td:eq(2)').find('div:eq(0)').text();

      match.date = date;
      match.team1 = team1;
      match.team2 = team2;
      match.venue = loc;

      console.log(match); // It displays Correctly

      (matches = window.matches || []).push({});
      matches = (window.matches || []).push(match);
     // console.log(matches[i])

});

console.log(matches); // All object values belong only to final index
2个回答

3
你一直在将同一个对象重复地推入数组中。
移动你的
var match = {};

into 放入循环中,以便每次创建一个新对象。
此外,我不确定您想要通过这样做实现什么:
(matches = window.matches || []).push({});
matches = (window.matches || []).push(match);

但您只想要:
matches.push(match);

这是一个最简单的示例,展示了你正在做的事情:
var match = {};
var i;
for (i = 0; i < 5; ++i) {
    match.i = i;         // Overwrites the previous `i` value on subsequent loops
    matches.push(match); // Pushes the *same object* onto the array
}
console.log(matches);    // Shows the same object, all with `i = 4`

相反,每次创建一个新的对象:

var i;
for (i = 0; i < 5; ++i) {
    var match = {};     // Creates a new object
    match.i = i;
    matches.push(match);
}
console.log(matches);

将此应用于您的代码:

var matches = [];

$('.SIsort').each(function (i, v) {
      console.log("type.."+typeof matches);
      var date = $(this).find('td:eq(0)').find('meta')[0].content;
      var team1 = $(this).find('td:eq(1)').find('div:eq(1)').text();
      var team2 = $(this).find('td:eq(1)').find('div:eq(3)').text();
      var loc = $(this).find('td:eq(2)').find('div:eq(0)').text();

      var match = {};
      match.date = date;
      match.team1 = team1;
      match.team2 = team2;
      match.venue = loc;

      console.log(match); // It displays Correctly

      matches.push(match);
});

console.log(matches);

侧记:这些行:
var match = {};
match.date = date;
match.team1 = team1;
match.team2 = team2;
match.venue = loc;

console.log(match); // It displays Correctly

matches.push(match);

可以合并成:
var match = {
    date: date,
    team1: team1,
    team2: team2,
    venue: loc
};

console.log(match); // It displays Correctly

matches.push(match);

我的错,谢谢Crowder.. :) - Human Bot

0
你的代码问题在于你只在循环外创建了一个match实例,并在每次迭代中更新相同的对象,然后将其添加到数组中。实际上,每当你想要添加一个条目到循环中时,你应该创建一个新的对象,所以在循环开始时创建一个新的对象,如下所示。
var matches = [];

$('.SIsort').each(function (i, v) {
   var match = {};
   // update match object and add to array
   matches.push(match);
}

应该就这样了 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接