我正在用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