我一直在尝试在typescript中编写一个简单的for循环:
j:any;
x=[1,2,3,4,5,6,7];
for(j in x){
console.log(x[j]);
}
即使我使用此关键字,我也会收到很多错误
1。'='预期。
2.找不到名字'j'。
3.模块解析失败:
您可能需要适当的加载程序来处理此文件类型。
| this.x = [1,2,3,4,5,6,7]; | } |
PlanningComponent.prototype.for = function(let){|如果(让 === void 0){let = j in this.x; } |的console.log(this.x [J]);
4.重复标识符j
5.意想不到的令牌。
请在我出错的地方纠正我。
答案 0 :(得分:1)
您必须添加
const
表示变量x和j:
const x = [1, 2, 3, 4, 5, 6, 7];
for (const j of x) {
console.log(j);
}
答案 1 :(得分:0)
j
将是代码第一行中未使用的标签,请将其丢弃。
然后在const
和for循环的条件中添加x
关键字,对于`j,像这样:
const x = [1, 2, 3, 4, 5, 6, 7];
for(const j in x) {
console.log(x[j]);
}
提示:for(var j in x)
也可以。阅读TypeScript for-in statement中的更多内容。在这种情况下,不要忘记使用var
,否则您将声明一个名为j
的全局变量。
答案 2 :(得分:0)
// you're assigning to a variable which was never declared
j:any;
// you're assigning to a variable which was never declared
x=[1,2,3,4,5,6,7];
for(j in x){
console.log(x[j]);
}
/*** correct version should be ***/
let j: number = 0;
const x: number[] = [1, 2, 3, 4, 5, 6, 7];
for(; j < x.length; i++) {
const num: number = x[j];
console.log({index: j, value: num});
}
for...in
shouldn't be used over arrays。