javascriptlearner
javascriptlearner

Reputation: 201

Uncaught TypeError: undefined is not a function when readind map in javascript

I have created a map in java script I am trying to get in else block and I get below error. I am not able to understand and debug this properly.

Uncaught TypeError: undefined is not a function
fruits : apple,orange,pineapple
countries:usa,uk,india,australia
cities:frankfurt,berlin,moscow

var map ={}; 

map['fruits'] = myObj1;
map['countries'] = myObj2;
map['cities'] = myObj2;

function get(k) {
    return map[k];
}

if{

//dosomething

}

else{
var test2=map.get('fruits');

}

Upvotes: 0

Views: 74

Answers (2)

Oleksandr T.
Oleksandr T.

Reputation: 77482

Try

var test2 = get('fruits');

because map does not have method get,

or change map object

var map = { get: function (key) { return this[key] }}; 

Upvotes: 1

Sizik
Sizik

Reputation: 1066

The get function isn't a member of map, so calling map.get('fruits') doesn't work. Either just call get('fruits') by itself, or make get a member of map:

map.get = function(k) {
    return this[k];
}

Upvotes: 0

Related Questions