can';在typescript中无法获取循环的
我正试图用TypeScript在VS代码中创建一个自定义的iterables。它根本不会遍历它。我做错了什么?我已将目标设置为can';在typescript中无法获取循环的,typescript,ecmascript-6,Typescript,Ecmascript 6,我正试图用TypeScript在VS代码中创建一个自定义的iterables。它根本不会遍历它。我做错了什么?我已将目标设置为es6,并尝试使用和不使用下层生成标志 // this works test("can iterate array", () => { let total = 0; for (let i of [1, 2, 3]) { total = total + i; } expect(total).toBe(6); }); f
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
我必须重新启动VS代码。下面所有的测试都通过了
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”,
“lib”:[
“es6”,
“dom”
],可能的重复我也尝试了更简单的'for(let I of numbers())`,避免了整个符号的事情,但这不起作用。更简单的是:for(let I of{[symbol.iterator]:function*(){yield 1;yield 2;yield 3;}{console.log(I);}这与浏览器兼容性有什么关系吗?我刚刚发现迭代器在web浏览器中可以工作,但在我的jest测试中不起作用。不知何故,我必须弄清楚如何让jest使用es6。