0

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.

Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
Gayathri
  • 1,776
  • 5
  • 23
  • 50
  • Possible duplicate of [TypeScript for-in statement](https://stackoverflow.com/questions/12950681/typescript-for-in-statement) – Jota.Toledo Sep 03 '17 at 15:59
  • I'm sort of wondering if you did any kind of reading or learning about TypeScript before starting to write your code. Declaring variables is very basic (actually in JavaScript as well as TypeScript). –  Sep 03 '17 at 17:49

3 Answers3

2

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);
}
porgo
  • 1,729
  • 2
  • 17
  • 26
0

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.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
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.

Hitmands
  • 13,491
  • 4
  • 34
  • 69