【问题标题】:Javascript: Hang-Man Function Not WorkingJavascript:Hang-Man 功能不起作用
【发布时间】:2015-04-23 08:23:59
【问题描述】:

我目前正在使用浏览器制作一个简单的刽子手游戏。

当用户点击一个按钮时,它会调用一个函数pickWord()

    <button onclick="pickWord()" id="restart">Pick A Word</button>

然后该函数从字典中选择一个随机单词,将其分配给一个变量,并为该单词创建空格 (_ _ _ _) 以放入 html 表中。

    function pickWord()
    {
        var word = dictionary[Math.floor(Math.random()*dictionary.length)];
        wordSpaces = "_" * word.length;
        document.getElementById('spaces').innerHTML = wordSpaces;

    }

这不起作用:表格上不显示空格。

我发了JSFiddle 来帮助解决问题。

【问题讨论】:

  • 至少在你的小提琴中,你的数组中的“Hangman”后面缺少一个逗号。你也会遇到问题,因为"_" * word.length; 不起作用。
  • 好的,谢谢!有没有办法让空格数=单词的长度?
  • 查看this question 以获得该解决方案。 Array(word.length).join('_');

标签: javascript html


【解决方案1】:

您不能将乘法应用于字符串和数字,因此您需要使用循环来构建wordSpaces 字符串。

dictionary 数组的第一行后面缺少一个逗号。

在您的 JSFiddle 中,javascript 代码被包装在 onLoad 函数中,因此您在全局范围内没有 pickWord。

更新:https://jsfiddle.net/24eqxLpn/1/

【讨论】:

  • 谢谢!这很有帮助
【解决方案2】:
function pickWord() {
    var word = dictionary[Math.floor(Math.random()*dictionary.length)];

    var wordSpaces = '';
    for(var i=0;i<word.length;i++) {
        wordSpaces += '_'; // append
    }

    document.getElementById('spaces').innerHTML = wordSpaces;

}

【讨论】:

  • 你能补充一些解释吗?
【解决方案3】:

你的第一个 pb 来自你的表,你错过了一个逗号, 之后 Javascript 崩溃。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2021-08-27
    • 2013-01-31
    • 2013-01-17
    • 2020-09-04
    • 2017-04-14
    相关资源
    最近更新 更多