這是將預先撰寫的陣列中的單個專案添加到表中的示例代碼。只有一個名稱元素,所以我只需要一個“< td>${people[i]}</td>”標簽來顯示名稱。
let people: string [] = ["Jack", "Michael"]
for (let i: number = 0; i < people.length; i ) {
document.getElementById ("buddies").innerHTML =
`<tr>
<td>${people[i]}
<tr>`;
}
那么如果我想使用一個類而不是簡單地將內容寫入陣列,我將如何獲得相同的結果?
class = Person{
public FirstName : string
public LastName : string
constructor (Firstname: string, Lastname: string) {
this.FirstName = Firstname;
this.LastName = Lastname;}
let people: Person [] = [
new Person ("Peter", "Parker")]
for (let i: number = 0; i < people.length; i ) {
document.getElementById ("table").innerHTML =
`<tr>
<td>${people[i]} //this is where the first name should be//
<td>${people[i]} //this is where the last name should be //
<tr>`;
}
我知道我的 < td> 標簽的當前內容是荒謬的,但我無法在仍然使用我的函式的同時將姓氏和名字分配給相應的標簽,該函式也在渲染串列中。在瀏覽器中打開時,我在表格行中得到 [object Object] 而不是“Peter Parker”。
朝著正確方向的推動將不勝感激。
uj5u.com熱心網友回復:
好吧,在這種情況下,people是一個類的實體陣列Person、 的物件Person,并且這個類具有屬性FirstName和LastName。
所以現在,當您在回圈中迭代時people,要訪問它的屬性,您應該執行people[i].FirstName和people[i].LastName。
for (let i: number = 0; i < people.length; i ) {
document.getElementById ("table").innerHTML =
`<tr>
<td>${people[i].FirstName} //this is where the first name should be//
<td>${people[i].LastName} //this is where the last name should be //
<tr>`;
}
所以你的代碼應該是這樣的:
<table id="table"></table>
<script>
// Made it with JS, but the class syntax is mostly the same in TS, since TS is a superscript of JS
class Person{
constructor (Firstname, Lastname) {
this.FirstName = Firstname;
this.LastName = Lastname;
}
}
let people = [new Person ("Peter", "Parker"), new Person ("Jhonny", "Johnson")]
for (let i = 0; i < people.length; i ) {
document.getElementById("table").innerHTML =
`<tr>
<td>${people[i].FirstName}
<td>${people[i].LastName}
<tr>`;
}
</script>
此外,您的代碼有一些錯誤,例如該類沒有結束括號,而且,要定義一個類,它只是
class Person{
...
}
并不是
class = Person{
...
}
更多示例可以在檔案中找到。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/403073.html
標籤:
