【问题标题】:How to display the content of an array using class attributes in TS?TS中如何使用类属性显示数组的内容?
【发布时间】:2022-01-04 07:27:44
【问题描述】:

这是将预先写入的数组中的单个项目添加到表中的示例代码。只有一个名称元素,所以我只需要一个“

${people[i]}”标签来显示名称。
    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>`;
    }

我知道我的

标签的当前内容是荒谬的,但我无法在仍然使用我的函数的同时将姓氏和名字分配给相应的标签,该函数也在渲染列表中。在我的浏览器中打开时,我在表格行中得到 [object Object] 而不是“Peter Parker”。

我们将不胜感激。

【问题讨论】:

    标签: arrays typescript function class


    【解决方案1】:

    嗯,在这种情况下,people 是类 Person 的实例数组,Person 的对象,并且该类具有属性 FirstNameLastName

    所以现在,当您在循环中迭代 people 时,要访问其属性,您应该执行 people[i].FirstNamepeople[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{
      ...
    }
    

    更多示例请参见docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-26
      • 2014-01-20
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多