将对象分配给数组,然后根据位置从数组调用它

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

本文关键字:数组 位置 调用 然后 对象 分配      更新时间:2023-09-26

我一直在研究这段代码,但我对为什么它不起作用感到困惑。我已经创建了三个"Geocache"对象,并将它们分配给一个名为"缓存"的数组。为了进行测试,我将变量"value"分配给缓存的索引1中的任何内容。然后,我将变量"挑逗"定义为的"长度"属性。

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;

这应该返回值"-79.505…",但我在预览中得到的是"未定义"。有没有人能帮我弄清楚这段代码有什么问题,因为我似乎不能弄清楚。

这是你的代码,javascript在代码片段的javascript部分。

和一个使用自调用函数来阻止全局泄漏的修复。

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