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

Javascript add object to an oustide array in a loop

我正在尝试将动态创建的 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

您重复将 相同的对象 推入数组。

移动你的

var match = {};

...第 行进入 循环,以便您每次都创建一个新对象。

另外,我不确定你想用这个实现什么:

(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);

您的代码存在的问题是,您在循环之外仅创建了 match 的一个实例,并在每次迭代中更新相同的对象,然后再将其添加到数组中。实际上你应该创建一个新对象,每次你想在你的循环中添加一个条目,所以在循环的开始创建一个新对象,如下所示。

var matches = [];

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

应该这样做 :)