gpt4 book ai didi

javascript - 从单词数组中选择一个随机单词

转载 作者:行者123 更新时间:2023-11-30 17:38:36 25 4
gpt4 key购买 nike

我正在研究以下程序。我的任务是将程序设置为选择一个随机词,这样用户就可以猜到我添加了以下 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

最佳答案

除了 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)
解释:

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: ["-", "-", "-", "-;"]

关于javascript - 从单词数组中选择一个随机单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21523023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com