2016-12-01 47 views
0

我正在用NSEW导航构建基本游戏。带有变量的Javascript对象

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

我m TRYING将对应于正确当前位置的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

你所做的另一种形式是如何你想通过LOC#.desc?我们能看到更多吗? loc + [currentLoc] + .desc绝对不会为你做任何事......是loc字符串吗?我们需要更多的帮助你。 –

+1

你能告诉我们什么'nav'和'loc'对象看起来像? –

+1

我猜你正在尝试做的是动态创建属性'loc1','loc2'等。它看起来像'obj ['loc'+ num]'其中'num'是1,2 ,或3等 – fredrover

回答

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