javascript - 函数参数未定义 - Javascript

标签 javascript parameters

我正在编写一个基于文本的小型 Angular 色扮演游戏,但遇到了一个我不知道如何解决的问题。问题出在这个函数上......

 function materia(mate, nam) {
      var matt = mate;
      console.log(matt);
      document.getElementById("menu").innerHTML = '<a href="#" onclick="examine(matt)">Examine ' + nam + '</a><a href="#" onclick="take(matt)">Take ' + nam + '</a><br><br><a href="#" onclick="eat(matt)">Eat/Drink ' + nam + '</a><a href="#" onclick="touch(matt)">Touch ' + nam + '</a>';
    }

该函数的引用:

var room = ['<a href="#" onclick="materia(0, \'water\')">Water</a> drips from the ceiling into <a href="#" onclick="materia(0,\'pools\')">small, murky pools</a> amongst the <a href="#" onclick="materia(1,\'stone\')"> tiles of stone</a>. The <a href="#" onclick="materia(1,\'brick walls\')">brick walls</a> are covered in <a href="#" onclick="materia(2,\'dark moss\')">dark moss</a> and seem to be slightly concave. <a href="#" onclick="materia(3,\'wood\')">Chunks of wet, termite infested wooden two by fours</a> lay on the ground.',

出于某种原因,当我调用函数检查并传递 matt 变量时,它说 matt 未定义。然而控制台日志显示 matt 等于 0。当我探索地牢直到我到达里面有水的房间并单击第一个标题为“水”的链接时,这一切都会发生。我不知道出了什么问题,但也许这里有人知道。这是完整的代码,以防问题出在其他地方。

<html>
<body>
<p id='main'></>
<p id='menu'></p>
<p id='footer'></p>
<script>

function entity(hp, mp, body, mind, soul, name, gear, gp, statPts, lvl, xp, powers, def) {
  this.hp = hp;
  this.mp = mp;
  this.body = body;
  this.mind = mind;
  this.soul = soul; 
  this.name = name;
  this.gear = gear;
  this.gp = gp;
  this.statPts = statPts;
  this.lvl = lvl;
  this.xp = xp;
  this.powers = powers;
  this.def = def;
}

var player = new entity(5, 5, 5, 5, 5, "DJ Khaled", ["Satchel", "Linen Shirt", "Plaid Boxers", "Leather Pants"], 100, 5, 1, 0, 0, 0);
var goblin = new entity(5, 5, 2, 2, 2, "Goblin", ["Pike", "Steel Buckler", "Leather Cap", "Snakeskin Banana Hammock"], 23, 0, 1, 14, 0, 0);

function startMenu() {
  document.getElementById("main").style.textAlign = "center";
  document.getElementById("footer").style.textAlign = "center";
  document.getElementById("menu").style.textAlign = "center";
  document.getElementById("main").innerHTML ='Adventurama<br><br><a href="#" onclick="playGame()">Play</a>';
}

function playGame() {
  document.getElementById("main").innerHTML = 'Enter name:<br><input id="charName"></input><button onclick="genChar()">Enter</button>';
} 

function genChar() {
  player.name = document.getElementById("charName").value;
  genChar2();
}

function genChar2() {
  document.getElementById("main").innerHTML = player.name + ' <br>Allocate your stats:<br><br>Body ' + player.body + ' <button onclick="statAlloc(1)">+</button> <button onclick="statAllocM(1)">-</button><br><br> Mind ' + player.mind + ' <button onclick="statAlloc(2)">+</button> <button onclick="statAllocM(2)">-</button><br><br> Soul ' + player.soul + ' <button onclick="statAlloc(3)">+</button> <button onclick="statAllocM(3)">-</button><br><br> Stat Points Left: ' + player.statPts + '<br><br><button onclick="mainGame()">Continue</button>';
}

function statAlloc(a) {
  if (player.statPts <= 0) {
    genChar2();
  } else {
    switch (a) {
      case 1:
        player.body += 1;
        player.statPts -= 1;
        break;  
      case 2:
        player.mind += 1;
        player.statPts -= 1;
        break;
      case 3:
        player.soul += 1;
       player.statPts -= 1;
        break;
      }
    }
   genChar2();
}

function statAllocM(a) {
  switch (a) {
   case 1:
      player.body -= 1;
      player.statPts += 1;
      break;  
   case 2:
      player.mind -= 1;
      player.statPts += 1;
      break;
   case 3:
      player.soul -= 1;
      player.statPts += 1;
      break;
  }
  genChar2();
}

function mainGame () {
  document.getElementById("main").innerHTML = '<a href="#" onclick="dungeon(-1)">Explore the Dungeons</a><br><br><a href="#" onclick="shop()">Buy some Gear</a><br><br><a href="#" onclick="city()">Explore the City</a><br><br><a href="#" onclick="character()">View your Character</a><br><br><a href="#" onclick="inventory()">Check your Inventory</a>';
  document.getElementById("footer").innerHTML = '';
}

var prevRoom = -1;

function dungeon(z) {
  var room = ['<a href="#" onclick="materia(0, \'water\')">Water</a> drips from the ceiling into <a href="#" onclick="materia(0,\'pools\')">small, murky pools</a> amongst the <a href="#" onclick="materia(1,\'stone\')"> tiles of stone</a>. The <a href="#" onclick="materia(1,\'brick walls\')">brick walls</a> are covered in <a href="#" onclick="materia(2,\'dark moss\')">dark moss</a> and seem to be slightly concave. <a href="#" onclick="materia(3,\'wood\')">Chunks of wet, termite infested wooden two by fours</a> lay on the ground.', 
              'The <a href="#" onclick="materia(1,\'stone bricks\')"> stone bricks and tiles</a> fade away into a cave full of <a href="#" onclick="materia(4,\'stalagmites\')">stalagmites</a>. In every nook and cranny, red flickering <a href="#" onclick="materia(5,\'candles\')">red, flickering candles</a> slowly melt away. The walls are covered in noir style artwork of monstrous beasts, rape, demons, and dismembered limbs. In the center of the room there is a <a href="#" onclick="materia(1,\'stone\')">large slab of stone</a>  with a pile of bloodstained oriental robes.',
              'Cracked marble tiles crawl forward alongside giant pillars that escalate beyond the farthest reaches of your eyesight. At the end of this corridor, two giant statues of godly figures pose in an eternal state of magnificence and glory.',
              'The entirery of this room has been sculpted into a jade dragon, coiled up and sleeping. The room is fairly small only being about twelve feet in diameter. From a pinhole in the ceiling, a trail of light streams down upon a stone altar, fixed onto the floor.',
              'Long lines of wooden bookcases containing hundreds of dusty leather tomes fill the cobweb ridden stone room. Stairs on all sides of the room lead to a wooden overhang with iron rails. A red pentogram on the ceiling drips fresh blood on the wood floor.'
             ];
  do {
    var ran = Math.floor(Math.random() * room.length);
  } while (ran == prevRoom)
  prevRoom = ran;
  if (z > -1) {
    document.getElementById("main"). innerHTML = room[z];
  } else {
    document.getElementById("main"). innerHTML = room[ran];
  }
  document.getElementById("menu"). innerHTML = '';
  document.getElementById("footer").innerHTML = '<br><a href="#" onclick="dungeon()">Keep Exploring</a><br><a href="#" onclick="mainGame()">Leave</a>';

}

/* 
Actions:
  kick, punch, talk, open, 
  close, examine, take, give, 
  throw, eat, touch
Materials: 
  0: water, 1: stone, 2: moss, 3: wood
  4: stalagite, 5: candle, 6: robes
  7: marble, 8: god statue, 9: jade
  10: altar, 11: bookcase, 12: 
  13: iron rail, 14: blood, 15: debris
*/

function materia(mate, nam) {
  var matt = mate;
  document.getElementById("menu").innerHTML = '<a href="#" onclick="examine(matt)">Examine ' + nam + '</a><a href="#" onclick="take(matt)">Take ' + nam + '</a><br><br><a href="#" onclick="eat(matt)">Eat/Drink ' + nam + '</a><a href="#" onclick="touch(matt)">Touch ' + nam + '</a>';
}

function examine(mate) {  
  var exam = ['You examine the water. The water is ordinary water save for a <a href="#" onclick="materia(15,\'dirt\')">miniscule amount of debris</a> floating around.',
                       'You examin the stone. Weathered and rough and greyish blue in hue, this is some fine stone.',
                       'You examine the moss. It is fairly damp and a deep foresty green. It is very soft.',
                       'You examine the wood. It is slightly coarse and grainy, somewhat splintery around the edges. It is a tannish, sandy color.',
                       'You examine the stalagmite. Bearing the resembelance of a mineral icicle, the stalagmite is rough, ivory and pretty pointy.',
                       'You examine the candle. It is somewhat stubby with lots of buildup melted wax around the top. Protruding from the top is a black wick.',
                       'You examine the robes. They are silky and flowy and the fabric is very thin. The white hems are very large and the rest of the material is decorated with beautiful art.',
                       'You examine the marble. The marble is so smooth, you can see a faint glossy reflection of yourself in it. It is a creamy white color with faint dark swirls.',
                       'You examine the statue. A nude, godly figure of exquisite physique has been depicted from this slab of marble. It stands about 10 feet tall.'
                       ];
  document.getElementById("menu").innerHTML = exam[mate];
}

function matt() {
  var n=0;
}

startMenu();











</script>
</body>
</html>   

最佳答案

问题在于,matt 仅在用户单击链接时才进行评估,然后上下文不再是函数materia,而是全局范围。由于在该范围内 matt 是一个函数(参见脚本末尾),因此您传递的是函数引用而不是数值。

一个快速修复方法是在插入 dom 的 anchor 元素中插入 matt 的实际值,如下所示:

function materia(mate, nam) {
    var matt = mate;
    console.log(matt);
    document.getElementById("menu").innerHTML =
        '<a href="#" onclick="examine(' + matt + ')">Examine ' + nam +
        '</a><a href="#" onclick="take(' + matt + ')">Take ' + nam +
        '</a><br><br><a href="#" onclick="eat(' + matt + ')">Eat/Drink ' + nam +
        '</a><a href="#" onclick="touch(' + matt + ')">Touch ' + nam + '</a>';
}

关于javascript - 函数参数未定义 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34244043/

相关文章:

android - 如何在Android中动态设置布局参数?

function - 在 golang 中,使用 net/http 时如何调用带和不带尾随括号的函数

javascript - Angular Firebase (AngularFire) CRUD 显示和编辑页面?

javascript - 如何在 Javascript 中按值(而不是引用)保存所选元素的 Node ?

javascript - 如何将<select>中的选项动态分组到optgroups中?

python - 有没有办法将 "array of strings"设置为函数中参数的类型?

Powershell 参数声明替代方案

javascript - 通过 JS 解析 URL 参数,但仅将前八个字符作为值添加到 HTML 表单中

javascript - 如何在一个页面上运行多个版本的 Zepto.js?

javascript - var 在 Foundation.util.touch.js 中未定义