Doc Holiday
Doc Holiday

Reputation: 10254

javascript object is undefined?

I'm getting "map is undefined", not sure why.
Am I passing a wrong variable, or is myMap wrongly declared?

var myMap = new Object();
$(things).each(function(){
   var thing= this.attributes.things.Value;
   alert("thing= " + thing);
   var totalThings= myMap[thing];
   alert("totalThings= " + totalThings);                
}); 

Upvotes: 0

Views: 11558

Answers (3)

lshettyl
lshettyl

Reputation: 8171

if thing is a string, may be you were trying to do:

myMap[things] = thing;
alert("totalThings = " + JSON.stringify(myMap, null, 4));

Upvotes: 0

kangoroo
kangoroo

Reputation: 359

you can do something like this

function myMap( thing ){
// properties and defaults 
this.thing = thing || 'default'
}

var myMapInstance = new myMap(whateverTheThingIs); 

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101594

Chances are myMap is defined, but myMap[thing] is not (since it's a virgin object with no properties). And since you're getting the value (and not setting it) you're getting an error.

// virgin object
var myObj = new Object();
console.log(JSON.stringify(myObj)); // "{}"

// therefore property "foo" doesn't exist
console.log(myObj['foo']);          // undefined

// but if we add it:
myObj['foo'] = 'bar';

// now it exists
console.log(myObj['foo']);          // "bar"

Upvotes: 4

Related Questions