12

I am absolute beginner on TypeScript. I want to initialize an array of numbers in TypeScript by "for" loop as you see in the following:

 public hours: number[];
 constructor() {
   for (let i: number = 1; i < 25; i++) {
      this.hours[i] = i;
    }
  }

I get an error: Cannot set property '1' of undefined. Could you please help me?

1
  • 1
    In the constructor: hours = new Array() Commented Apr 26, 2017 at 14:37

2 Answers 2

19

This line:

public hours: number[];

Does not create a new array, it only declares it.
If you compile this code:

class MyClass {
    public hours: number[];

    constructor() {
        for (let i: number = 1; i < 25; i++) {
            this.hours[i] = i;
        }
    }
}

You get:

var MyClass = (function () {
    function MyClass() {
        for (var i = 1; i < 25; i++) {
            this.hours[i] = i;
        }
    }
    return MyClass;
}());

As you can see, this.hours isn't being assigned.

So you need to do this:

constructor() {
    this.hours = [];

    for (let i: number = 1; i < 25; i++) {
        this.hours[i] = i;
    }
}

Or:

public hours: number[] = [];
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much.
1

hours isn't set to any value. You can create a new array in the constructor, or set hours to an empty array:

public hours: number[] = [];
constructor() {
   for (let i: number = 1; i < 25; i++) {
      this.hours[i] = i;
   }
}

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.