【问题标题】:can't get for..of loop working in typescript无法在打字稿中使用 for..of 循环
【发布时间】:2018-10-21 13:18:03
【问题描述】:

我正在尝试使用 TypeScript 在 VS Code 中创建自定义迭代。它根本不会遍历它。我究竟做错了什么?我已将目标设置为 es6 并尝试使用和不使用下级生成标志。

// this works
test("can iterate array", () => {
    let total = 0;
    for (let i of [1, 2, 3]) {
        total = total + i;
    }
    expect(total).toBe(6);
});

function* numbers() {
    yield 1;
    yield 2;
    yield 3;
}

let myInterable = {
    [Symbol.iterator]: numbers
};

// this does NOT work
test("can iterate custom", () => {
    let total = 0;
    for (let i of myInterable) {
        total = total + i;
    }
    expect(total).toBe(6);
});

这是我的 tsconfig.json 的相关部分...

"compilerOptions": {
  "module": "esnext",
  "target": "es6",
  "lib": [
    "es6",
    "dom"
  ],
  "sourceMap": true,
  "allowJs": true,
  "jsx": "react",
  "moduleResolution": "node",
  "rootDir": "src",
  "forceConsistentCasingInFileNames": true,
  "noImplicitReturns": true,
  "noImplicitThis": true,
  "noImplicitAny": true,
  "strictNullChecks": true,
  "suppressImplicitAnyIndexErrors": true,
  "noUnusedLocals": false

【问题讨论】:

  • 我还尝试了更简单的`for (let i of numbers())`,避免了整个符号的事情,但这也不起作用
  • 更简单: for (let i of { [Symbol.iterator]: function* () { yield 1; yield 2; yield 3; } }) { console.log(i); }
  • 和浏览器兼容性有关系吗?
  • 刚刚发现这个迭代器的东西在网络浏览器中工作,但在我的笑话测试中却不工作。不知何故,我必须弄清楚如何开玩笑才能使用 es6。

标签: typescript ecmascript-6


【解决方案1】:

我不得不重新启动 VS Code。以下所有测试均通过。

test("can iterate array", () => {
    let total = 0;
    for (let i of [1, 2, 3]) {
        total = total + i;
    }
    expect(total).toBe(6);
});

function* numbers() {
    yield 1;
    yield 2;
    yield 3;
}

test("can iterate custom", () => {
    let total = 0;
    for (let i of numbers()) {
        total = total + i;
    }
    expect(total).toBe(6);
});

test("can iterate custom iterable", () => {
    let x = {
        [Symbol.iterator]: numbers
    };
    let total = 0;
    for (let i of x) {
        total = total + i;
    }
    expect(total).toBe(6);
});

在 package.json 中...

“目标”:“es6”, “库”:[ "es6", “dom” ],

【讨论】:

    猜你喜欢
    • 2022-11-02
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 2023-01-19
    • 2020-07-10
    相关资源
    最近更新 更多