【发布时间】: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。