Hướng dẫn javascript loop add object to array - vòng lặp javascript thêm đối tượng vào mảng

Bạn liên tục đẩy cùng một đối tượng vào mảng.same object into the array.

Di chuyển của bạn

var match = {};

... xếp vào vòng lặp để bạn tạo một đối tượng mới mỗi lần.

Ngoài ra, tôi không chắc chắn những gì bạn đang cố gắng đạt được với điều này:

[matches = window.matches || []].push[{}];
matches = [window.matches || []].push[match];

Nhưng bạn chỉ muốn:

matches.push[match];

Đây là một ví dụ tối thiểu về những gì bạn đang làm:

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`

Thay vào đó, hãy tạo một đối tượng mới mỗi lần:

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

Áp dụng nó cho mã của bạn:

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];

Lưu ý bên: Những dòng sau:

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

console.log[match]; // It displays Correctly

matches.push[match];

có thể được kết hợp thành:

var match = {
    date: date,
    team1: team1,
    team2: team2,
    venue: loc
};

console.log[match]; // It displays Correctly

matches.push[match];

0 điểm

Gần 10 năm

Tôi đã sử dụng một vòng lặp để tạo một mảng các tên biến:

title = []; for [var i = 1; i
for [var i=1; i

Bài Viết Liên Quan

Chủ Đề