我有一个函数可以将多个JSON对象保存到Type" 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;
}
答案 0 :(得分:3)
首先需要定义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]);