【问题标题】:ES5 vs ES6 Javascript for ArraysES5 vs ES6 Javascript 用于数组
【发布时间】:2016-08-01 21:43:40
【问题描述】:

我正在尝试将以下内容转换为工作,但我认为这是一个 Es5/ES6 问题。帮助表示赞赏。

this.rows = Array.from(Array(Math.ceil(this.subCategoryModels.length / 3)).keys());

我目前遇到打字错误:

[ts] 
Property 'from' does not exist on type 'ArrayConstructor'.
any

和

[ts] 
Property 'keys' does not exist on type 'any[]'.
any

【问题讨论】:

  • “我认为这是一个 Es5/ES6 问题” - 你是想为 ES5 还是 ES6 编写? Array.from() 和 .keys() 都是 ES6 方法,所以显然它们在 ES5 中不起作用。
  • 尝试插入“新”,例如:“Array.from(new Array(Math...”) 看看是否有帮助。
  • 我尝试以下操作,但仍然遇到相同的错误。 this.rows = Array.from(new Array(Math.ceil(this.subCategoryModels.length / 3)).keys());
  • 这行得通,但我不认为它很优雅。 for (var index = 0; index < Math.ceil(this.subCategoryModels.length / 3); index++) { this.rows.push(index); }

标签: javascript arrays typescript ecmascript-6 es5-shim


【解决方案1】:

类型“ArrayConstructor”上不存在属性“from”。

这表明您希望在编译为 ES5 的同时使用 ES6 类型定义。

TypeScript 最新推荐lib 选项:

"compilerOptions": {
    "target": "es5",
    "lib": ["es6", "dom"]
}

更多

https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html#lib-option

【讨论】:

    【解决方案2】:

    由于您看到这些错误,我假设您正在编译到 ES5。您可以使用typings 让 Typescript 识别数组的 es2015 函数。

    首先,安装typings(如果尚未安装)。

    npm install typings --global

    安装类型后,为 ES2015 数组函数安装类型类型定义。

    typings install -SG env~es2015-array

    如果您的目标浏览器不支持新的 Array 函数,您还需要添加一个 polyfill。

    【讨论】:

      【解决方案3】:

      我最终做了以下事情:

      html

        <ion-row *ngFor="let trio of getTriples()">
          <ion-col *ngFor="let item of trio" (click)="itemTapped(item)">
            <div class="row responsive-md">
              <div id="icon-image-{{item.id}}"><img src="data:image/png;base64,{{item.icon}}" height="75" width="75" /></div>
              <p>{{item.name}}</p>
            </div>
          </ion-col>
        </ion-row>
      

      打字稿

        getTriples() {
          let triples = [];
          let length = this.subCategoryModels.length;
          for (let i = 0; i < length; i += 3) {
            let trio = [];
            trio.push(this.subCategoryModels[i]);
            if (i + 1 < length) {
              trio.push(this.subCategoryModels[i + 1]);
            }
            if (i + 2 < length) {
              trio.push(this.subCategoryModels[i + 2]);
            }
            triples.push(trio);
          }
          return triples;
        }
      

      【讨论】:

        猜你喜欢
        • 2019-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-06
        • 2015-04-16
        • 1970-01-01
        • 1970-01-01
        • 2018-04-05
        相关资源
        最近更新 更多