从一组单词中选择一个随机单词

时间:2014-02-03 08:52:20

标签: javascript

我正在研究以下计划。我的任务是设置程序选择一个随机单词,然后用户可以猜测它我添加了以下math.random()方法,但它在这里不起作用是代码:

var words_to_be_guessed = ["VIENNA", "HELSINKI", "COPENHAGEN",
                           "LONDON", "BERLIN", "AMSTERDAM"] ;

// here is what I added
var words_to_be_guessedd = words_to_be_guessed[Math.floor(Math.random()*words_to_be_guessed.lenght)];

var guessed_characters = [ '-', '-', '-', '-', '-', '-', '-', '-', '-', '-',
                           '-', '-', '-', '-', '-', '-', '-', '-', '-', '-',
                           '-', '-', '-', '-', '-', '-', '-', '-', '-', '-' ] ;

guessed_characters = guessed_characters.slice(0, word_to_be_guessed.length);

function string_array_to_string(given_array_of_strings){
   var string_to_return = "";
   for (string_index in given_array_of_strings){
      string_to_return = string_to_return + given_array_of_strings[string_index];
   }
   return string_to_return;
}

我明白了:

enter image description here

2 个答案:

答案 0 :(得分:1)

您错误拼写lengthlenght

var words_to_be_guessedd = words_to_be_guessed[
    Math.floor(Math.random()*words_to_be_guessed.length)];

这应该有用。

答案 1 :(得分:1)

除了length中的拼写错误之外,这一行还有一个错字:

guessed_characters = guessed_characters.slice(0, word_to_be_guessed.length);

应该是:

guessed_characters = guessed_characters.slice(0, words_to_be_guessed.length);
                                                     ^

此外,构建所需长度的破折号数组的更简单方法是:

Array(5).join('-').split('');

(其中5是所需的长度,在您的情况下,word_to_be_guessed.length
Exlanation:

Array(5)      // Create an array with 5 `undefined` elements. Result: [undefined, undefined, undefined, undefined, undefined];
  .join('-')  // Join these empty elements with a dash.       Result: "-----";
  .split(''); // Split this string at every character.        Result: ["-", "-", "-", "-;"]