我正在尝试使用每个循环将对象推入数组,而对象的数量恰好在最后,对象中的数据与最后一个条目重复。
当我在循环内记录对象时,它会给我两组数据,第一组是正确的,第二组是循环的最后一组数据。
我尝试将数据记录到控制台,但这确实给了我很奇怪的值。
$.getJSON(url, function(data) {
var entry = data.feed.entry;
var nietos = [];
var obj = {};
$(entry).each(function(){
var title = String(this.gsx$title.$t);
var lastName = String(this.gsx$lastname.$t);
var firstName = String(this.gsx$firstname.$t);
var email = String(this.gsx$email.$t);
var department = String(this.gsx$department.$t);
console.log(lastName);
obj["title"] = title;
obj["lastName"] = lastName;
obj["firstName"] = firstName;
obj["email"] = lastName;
obj["department"] = department;
//console.log(obj);
/*
(index):345 {title: "Cook II", lastName: "Woon", firstName: "Ra", email: "Wson",
department: "LR"}department: "WL Span"email: "Zuniga"firsame: "Lea"lastName: "Zga"title: "Regular Teer"__proto__: Object*/
//nietos.push(obj);
});
// console.log(nietos);
//97: {title: "Regular Teacher", lastName: "Zga", firstName: "Leticia", email: "Zuga", department: "WL S"}
});
预期:
{title: "Teacher", lastName: "Teacher1", firstName: "Teachername", email: "email1@gmail.com",},
{title: "Teacher2", lastName: "Teacher2", firstName: "Teachername2", email: "email2@gmail.com",},,
{title: "Teacher3", lastName: "Teacher3", firstName: "Teachername3", email: "email3@gmail.com",},
实际输出:
{title: "Teacher3", lastName: "Teacher3", firstName: "Teachername3", email: "email3@gmail.com",},
{title: "Teacher3", lastName: "Teacher3", firstName: "Teachername3", email: "email3@gmail.com",},
{title: "Teacher3", lastName: "Teacher3", firstName: "Teachername3", email: "email3@gmail.com",},
答案 0 :(得分:1)
您只能使用var obj = {};
创建一个对象,然后在“循环”中修改该对象,并将对该对象的引用添加到数组中。
在每次循环迭代中(在var obj = {}
回调内部)创建一个新的.each
。
作为旁注,let profesor = {};
会更好...