-4

I want to create an associative array within the constructor. But the below code throws error. Uncaught TypeError: Cannot set property 'num' of undefined

class Validate{

    constructor(){

        this.name['num'] = ['one','two'];
    }
    display() {




        console.log(this.name['num']);
    }



}
Dilkush
  • 113
  • 1
  • 2
  • 15

2 Answers2

3

Javascript has no associative array, but Object literal can be used as an alternative. Here, you need to define the object before using it.

class Validate{
    constructor(){
        this.name={}//define this.name
        this.name['num'] = ['one','two'];
    }
    display() {
        console.log(this.name['num']);
    }
}
n00dl3
  • 21,213
  • 7
  • 66
  • 76
0

You will initialize name and after that use property of your object . In this case name is not defined and you try to set property of undefined.

class Validator
{
  
  constructor(){

        this.name = {num :['one','two']} ;
        
    }
    display() {


       

        console.log(this.name['num']);
    } 
}
 var validator = new Validator();
validator.display();