Jacky Hoang Jacky Hoang - 28 days ago 7
Javascript Question

Assigning objects to an array, then call it from the array based on position

I've been working on this code but am puzzled as to why it doesn't work. I've created three "Geocache" objects and assigned them to an array called 'caches'. To test, I've assigned the variable "value" to whatever is in index 1 of caches. I then defined the variable "tease" as the 'lony' property of value.



function Geocache (lat, lon, disc){
this.laty=lat;
this.lony=lon;
this.disc=disc;
}


var loc1=new Geocache(43.77416104496804, -79.50804830784301, "lifesci building");
var loc2=new Geocache(43.77381242916627, -79.50533927673797, "lassonde building");
var loc3=new Geocache(43.77305321438563, -79.50353146786193, "vari hall");
var caches=[loc1,loc2,loc3];

var value = caches[1];
var tease=value.lony;





This should spit back the value of "-79.505..." but instead I get an "undefined" in the preview.
Can someone please help me figure out what is wrong with this code because I can't seem to figure it out.

Answer

Here is you code, with the javascript in the javascript part of the snippet.

And a fix to use a self invoking function to stop global leak.

function Geocache (lat, lon, disc){
  this.laty=lat;
  this.lony=lon;
  this.disc=disc;
}

(function () {  
  var loc1=new Geocache(43.77416104496804, -79.50804830784301, "lifesci building");
  var loc2=new Geocache(43.77381242916627, -79.50533927673797, "lassonde building");
  var loc3=new Geocache(43.77305321438563, -79.50353146786193, "vari hall");
  var caches=[loc1,loc2,loc3];

  var value = caches[1];
  var tease=value.lony;
  console.log(tease);
})();

Comments