2016-12-01 56 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);}