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.

2
  • Possible duplicate of TypeScript for-in statement Commented Sep 3, 2017 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). Commented Sep 3, 2017 at 17:49

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.