带有变量的Javascript对象

时间:2016-12-01 03:48:26

标签: javascript javascript-objects

我正在使用NSEW导航构建基本游戏。

  • 每个NSEW按钮都会更改当前位置的编号1,2,3等。
  • 每个位置都有一个与之关联的对象,名为loc1,loc2,loc3等。
  • 每个对象都有一个需要显示的描述,loc1.desc,loc2.desc等。
  • 我的显示功能正常,我的导航,但是...

尝试将与正确当前位置对应的loc#.desc值传递给函数。 (这是Javascript,顺便说一句)。目前,它看起来像这样:

function nextLoc(dir) { var newLoc = nav[currentLoc][dir]; currentLoc=newLoc; displayMessage(loc[currentLoc].desc);}

我希望它输入当前位置的号码并将其传递给displayMessage函数。我已经尝试了很多不同的方法,但它仍然不打印描述。如果我硬编码数字(loc2.desc)或只是传递currentLoc,它会工作,返回正确的对象描述或currentLoc数字。我也试过了:

loc+[currentLoc]+.desc

有办法做到这一点吗?我已经搜索并尝试了所有不同的方法来找到这个,但我找不到这个具体的问题,此时,我只是输了!非常感谢任何帮助!!

在回答评论时,这里是整个js文件:

//Location prototype    
function Location(id, desc){
this.id = id;
this.desc = desc;}
//Location objects
var loc2 = new Location(2, "Circus");
var loc1 = new Location (1, "Zoo");
var loc0 = new Location (0,"You entered the park here");

 var currentLoc = 0;
 var EAST  = 0;
 var WEST  = 1;
 var NORTH = 2;
 var nav = [ // E,W,N,S
     /*Current Location*/ 
     /* 0 */ [2,1,4,-1],
     /* 1 */ [0,-1,3,-1],
     /* 2 */ [-1,0,5-1],
     /* 3 */ [4,-1,-1,1],
     /* 4 */ [5,3,-1,0],
     /* 5 */ [-1,4,-1,2],
     ];        
  // Directional Button Event Handlers
 function btnEast_click() {nextLoc(EAST);}
 function btnWest_click() {nextLoc(WEST);}
 function btnNorth_click() {nextLoc(NORTH);}
 function nextLoc(dir) {
    var newLoc = nav[currentLoc][dir];
    currentLoc=newLoc;
    displayMessage(loc[currentLoc].desc);}

 // Utility Function(s)
 function displayMessage(msg) {
    var target = document.getElementById("taMain");
    target.value = msg + "\n\n" + target.value;
 }       

1 个答案:

答案 0 :(得分:0)

你非常接近能够在地图对象中进行命名查找。而不是创建一堆独立的位置(在浏览器中,最终作为window对象的属性,所以有一个我选择不追求的途径会让你使用它们。

我在下面做的是为静态位置创建一个对象。另一种方法是使用这样的符号,这实际上会导致相同的行为,但可能更容易理解正在发生的事情:

var locations = [];
locations['loc2'] = new Location(2, "Circus");
locations['loc1'] = new Location(1, "Zoo");
locations['loc0'] = new Location(0, "You entered the park here.");

同样可行的是删除' loc'键上的前缀,然后你可以写这样的东西:

var locations = [];
locations.add = function(id, desc){ locations[id] = new Location(id, desc)}
locations.add(0, "You entered the park here.") 

// and your navigation method looks like this then
function nextLoc(dir){
    var newLoc = nav[currentLoc][dir];
    currentLoc=newLoc;
    displayMessage(locations[currentLoc].desc);
}

另一种形式类似于你迄今为止所做的事情

var locations = {
   loc2 : new Location(2, "Circus"), 
   loc1 : new Location (1, "Zoo"),
   loc0 : new Location (0,"You entered the park here")
};

 function nextLoc(dir) {
    var newLoc = nav[currentLoc][dir];
    currentLoc="loc"+newLoc;
    displayMessage(locations[currentLoc].desc);}