Reputation: 1906
I have been trying to write a simple for loop like below in typescript :
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.
2. Cannot find name 'j'.
3.Module parse failed:
You may need an appropriate loader to handle this file type.
| this.x = [1, 2, 3, 4, 5, 6, 7]; | } |
PlanningComponent.prototype.for = function (let) { | if (let === void 0) { let = j in this.x; } | console.log(this.x[j]);
4.Duplicate identifier j
5.Unexpected token.
Please correct me where i went wrong.
Upvotes: 0
Views: 800
Reputation: 14199
// 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.Upvotes: 0
Reputation: 73444
j
will be an unused label in the first line of your code, discard it.
Then add the const
keyword in both x
and in the condition of the for loop, for `j, like this:
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. Read more in TypeScript for-in statement. Do not forget to use var
though in that case, otherwise you will declare a global variable, named j
.
Upvotes: 0
Reputation: 1737
You must add
const
for variables x and j:
const x = [1, 2, 3, 4, 5, 6, 7];
for (const j of x) {
console.log(j);
}
Upvotes: 2