[英]For loop in typescript. “= expected”
I have been trying to write a simple for loop like below in typescript : 我一直在尝试在typescript中编写一个简单的for循环,如下所示:
j:any;
x=[1,2,3,4,5,6,7];
for(j in x){
console.log(x[j]);
}
I get so much errors even when i use this keyword 1.'=' expected. 即使使用此关键字1,也会出现很多错误。
2. Cannot find name 'j'. 2.找不到名称“ j”。
3.Module parse failed: You may need an appropriate loader to handle this file type. 3.模块解析失败:您可能需要适当的加载器来处理此文件类型。
|
| this.x = [1, 2, 3, 4, 5, 6, 7];
this.x = [1,2,3,4,5,6,7]; |
| } |
} |
PlanningComponent.prototype.for = function (let) { |PlanningComponent.prototype.for =函数(let) if (let === void 0) { let = j in this.x;
if(let === void 0){让= j在this.x; } |
} | console.log(this.x[j]);
的console.log(this.x [J]);
4.Duplicate identifier j 4.重复的标识符j
5.Unexpected token. 5,意外令牌
Please correct me where i went wrong. 请纠正我哪里出错了。
You must add 您必须添加
const
for variables x and j: 对于变量x和j:
const x = [1, 2, 3, 4, 5, 6, 7];
for (const j of x) {
console.log(j);
}
j
will be an unused label in the first line of your code, discard it. j
将是代码第一行中未使用的标签,请将其丢弃。
Then add the const
keyword in both x
and in the condition of the for loop, for `j, like this: 然后在
x
和for循环的条件下(对于`j)添加const
关键字,如下所示:
const x = [1, 2, 3, 4, 5, 6, 7];
for(const j in x) {
console.log(x[j]);
}
Tip: for(var j in x)
will work too. 提示:
for(var j in x)
也可以使用。 Read more in TypeScript for-in statement . 在TypeScript for-in语句中了解更多信息。 Do not forget to use
var
though in that case, otherwise you will declare a global variable, named j
. 在这种情况下,请不要忘记使用
var
,否则您将声明一个名为j
的全局变量。
// 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 . for...in
不应在array上使用 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.