javascript object is undefined? - Stack Overflow

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

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);                
}); 

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);                
}); 
Share Improve this question edited Sep 5, 2013 at 12:07 Roko C. Buljan 207k41 gold badges327 silver badges339 bronze badges asked Sep 5, 2013 at 12:01 Doc HolidayDoc Holiday 10.3k32 gold badges102 silver badges153 bronze badges 6
  • 2 It seems like you're accessing thing field of an empty object: myMap[thing] – mishik Commented Sep 5, 2013 at 12:03
  • What error message exactly are you getting? myMap looks OK apart from that you could have shortened the constructor invocation to a {} literal – Bergi Commented Sep 5, 2013 at 12:04
  • 2 I don't see anything called map in that snippet. – Ingo Bürk Commented Sep 5, 2013 at 12:04
  • true that, what is thing by the way? – kangoroo Commented Sep 5, 2013 at 12:04
  • @kangoroo thing is a string – Doc Holiday Commented Sep 5, 2013 at 12:06
 |  Show 1 more ment

3 Answers 3

Reset to default 4

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"

you can do something like this

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

var myMapInstance = new myMap(whateverTheThingIs); 

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742394382a4435648.html

相关推荐

  • javascript object is undefined? - Stack Overflow

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

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信