【问题标题】:what is the meaning of syntax [] in typescript打字稿中语法[]的含义是什么
【发布时间】:2018-12-11 14:26:24
【问题描述】:

我想使用 ionic 示例应用来构建网络应用。有一部分示例代码是用打字稿编写的。我无法理解代码的含义 这[f] = 字段[f] 你能解释一下这段代码的含义吗?

这个ts文件的完整代码是:

  /**
 * A generic model that our Master-Detail pages list, create, and delete.
 *
 * Change "Item" to the noun your app will use. For example, a "Contact," or 
 a
 * "Customer," or a "Animal," or something like that.
 *
 * The Items service manages creating instances of Item, so go ahead and 
rename
 * that something that fits your app as well.
 */
export class Item {

  constructor(fields: any) {
    // Quick and dirty extend/assign fields to this model
    for (const f in fields) {
      // @ts-ignore
      this[f] = fields[f];
    }
  }

 }

export interface Item {
  [prop: string]: any;
}

【问题讨论】:

  • for in 循环的上下文中,ffields 对象的标识符键,this[key] = fields[key] 正在将值从fields 复制到this

标签: javascript angularjs typescript ionic-framework


【解决方案1】:

这是属性访问的括号表示法。您可以在 MDN here了解更多信息

【讨论】:

    【解决方案2】:

    把它想象成一个通用的构造函数。 它所做的是在函数的范围内迭代一个别名为“字段”的对象的成员,并将值分配给“this”,这是正在创建的对象。 例如,如果传递的对象是:

    var fields= {mem1: 1, mem2: 'marios'};
    
    the code would then
    
    for (const f in fields) {
          this[f] = fields[f];
          // 1st iteration would be
          // this[mem1] =  fields[mem1]; -> this[mem1] will create the property to the new object
          // fields[mem1] will read the value, so it created the prop and copies the value 
        }
    

    【讨论】:

      【解决方案3】:

      您正在查看动态属性访问器。假设“fields”是{first: 1, second: 2},代码相当于:

      this.first = fields.first this.second = fields.second

      所以简而言之,它将字段的所有可枚举属性分配给这个。

      MDN web docs: Property accessor

      【讨论】:

        猜你喜欢
        • 2017-01-23
        • 1970-01-01
        • 2017-03-11
        • 2022-11-16
        • 2017-05-25
        • 1970-01-01
        • 1970-01-01
        • 2016-04-08
        • 2018-06-12
        相关资源
        最近更新 更多