我正在用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;
}
你所做的另一種形式是如何你想通過LOC#.desc?我們能看到更多嗎? loc + [currentLoc] + .desc絕對不會爲你做任何事......是loc字符串嗎?我們需要更多的幫助你。 –
你能告訴我們什麼'nav'和'loc'對象看起來像? –
我猜你正在嘗試做的是動態創建屬性'loc1','loc2'等。它看起來像'obj ['loc'+ num]'其中'num'是1,2 ,或3等 – fredrover