-4
private seats: number[][] = [[10],[10]];
        for(let i:number=0; i < 10; i++)
        for(let j:number=0;j<10;j++)
            {
                this.seats[i][j] = '_';
            }

This is giving me an error

this.seats[i][j] = '_" TypeError: Cannot set property '0' of undefined how do i solve it?

Sammy
  • 25
  • 1
  • 6
  • http://www.typescriptlang.org/docs/home.html – jonrsharpe Sep 09 '17 at 10:11
  • i have gone through it but I could not find anything... i Am getting an error **this.seats[i][j] = '-'; ^ TypeError: Cannot set property '0' of undefined** @jonrsharpe – Sammy Sep 09 '17 at 10:16
  • 1
    Then give a [mcve] **of that attempt**. It looks like you've created an empty array as `seats`, in which case `seats[i]` will be `undefined`. – jonrsharpe Sep 09 '17 at 10:18
  • can you please code it for me ? @jonrsharpe would be of great help. I want the above code in typescript it is in java – Sammy Sep 09 '17 at 10:20
  • No; SO is **not** a code-writing service. Also that's not JavaScript; if it was, it would *already work* in TypeScript, which is a superset of JS. – jonrsharpe Sep 09 '17 at 10:20
  • i have just defined it as **private seats: number[][] = [[10],[10]]; for(let i:number=0; i < 10; i++) for(let j:number=0;j<10;j++) this.seats; { this.seats[i][j] = '_'; } }** For this i am getting the above error @jonrsharpe – Sammy Sep 09 '17 at 10:24
  • Please [edit] the question with correct formatting. But obviously that won't work, `[10]` doesn't create an array of length ten, it creates an array of length one with a single number in it. Again, read the basic documentation about the language you're trying to use; guessing is unlikely to be terribly productive. – jonrsharpe Sep 09 '17 at 10:25
  • I have editted it @jonrsharpe – Sammy Sep 09 '17 at 10:30
  • You have, but I've already told you why that won't work. You want to create an array of length ten, not an array with ten in it, so see e.g. https://stackoverflow.com/q/41139763/3001761 – jonrsharpe Sep 09 '17 at 10:31

1 Answers1

0

First of all, you're creating a 2d number array. So you can't assign _ as it is a string. Secondly, you're not initializing the secondary array

Try the following code:

private seats: number[][] = []; // 2d array is just an array

for(let i:number=0; i < 10; i++) {
    this.seats[i] = []; // you need to init the inner array

    for(let j:number=0; j<10; j++) {
        this.seats[i][j] = i;
    }
}
adiga
  • 34,372
  • 9
  • 61
  • 83