2015-04-23 50 views
-4

我目前正在使用瀏覽器做一個簡單的掛人遊戲。Javascript:掛人功能不工作

當用戶點擊一個按鈕,它調用一個功能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來幫助解決問題。

+1

至少在你的小提琴,你在你的數組中的「劊子手」後缺少一個逗號。你也會遇到問題,因爲'「_」* word.length;'不起作用。 – krillgar

+0

好的,謝謝!有沒有辦法讓空格的數量=單詞的長度? – JoshK

+1

查看[此問題](http://stackoverflow.com/questions/1877475/repeat-character-n-times)該解決方案。 'Array(word.length).join('_');' – krillgar

回答

1

您不能將乘法應用於字符串和數字,因此您需要使用循環來構建wordSpaces字符串。

dictionary數組中的第一行後面沒有逗號。

在你的JSFiddle中,javascript代碼被封裝在onLoad函數中,所以你在全局範圍內沒有pickWord。

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

+0

謝謝!這有很大幫助 – JoshK

0
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; 

} 
+0

你可以添加一些解釋嗎? –

0

你的第一個PB來自於你的表,你錯過了一個逗號之後, 的Javascript崩潰。