Typescript数组未定义



我得到了一个函数,它应该将多个JSON对象保存到"Contact"类型的数组中

getContacts(){
let self = this;
$.ajax({
type: "GET",
url: "/chat/contacts/",
dataType:"json",
success: function(response){
let obj = response;
let i = 1;
let contacts: Contact[] = [];
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
let val = obj[key];
contacts[i].id = val["id"]; //<-- contacts[i] is undefinded
contacts[i].partner = val["partnerId"];
contacts[i].name = val["name"];
contacts[i].type = val["type"];
console.log(contacts[i]);
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}

在标记的点上写着

联系人[i]是未定义的

我必须如何初始化数组才能使其工作?

这是联系人类别:

class Contact extends BaseModel{
static CCO_ID = "id";
static CCO_PARTNER = "partner";
static CCO_NAME = "name";
static CCO_TYPE = "type";

partner: Number;
name: String;
type: Number;
}

您需要首先定义contacts[i]是一个对象,然后使用它的属性。

还有一件事,您从索引1开始,在Javascript数组中,索引从0开始。如果这不是故意的,请注意。

let val = obj[key];
contacts[i] = new Contact(); // <-- Look here
contacts[i].id = val["id"];
contacts[i].partner = val["partnerId"];
contacts[i].name = val["name"];
contacts[i].type = val["type"];
console.log(contacts[i]);

最新更新