[英]How do I create a function that shall assign a random string (coming from an array) to a certain variable?
No result is being produced by the codes below.以下代码不会产生任何结果。 I'm trying to assign a random item from an array to the constant called palindromeGenerator, and this word will be evaluated as a palindrome word or not (for which I'm yet to figure out the codes).
我正在尝试将数组中的随机项分配给名为 palindromeGenerator 的常量,并且这个词将被评估为回文词或不被评估(我还没有弄清楚代码)。
const palindromeGenerator = (random) => { var palindromeArray = [ "racecar", "noon", "mom", "tenet", "sagas", "hill", "programs", "computer", "internet" ]; var random = Math.floor(Math.random() * 10); if (random == 0) { palindromeArray[0]; }; else if (random == 1) { palindromeArray[1]; }; else if (random == 2) { palindromeArray[2]; }; else if (random == 3) { palindromeArray[3]; }; else if (random == 4) { palindromeArray[4]; }; else if (random == 5) { palindromeArray[5]; }; else if (random == 6) { palindromeArray[6]; }; else if (random == 7) { palindromeArray[7]; }; else if (random == 8) { palindromeArray[8]; }; else { palindromeArray[9]; }; } palindromeGenerator;
You do not return anything so nothing happens with the function call.您不返回任何内容,因此 function 调用不会发生任何事情。 You are also not calling the function.
您也没有调用 function。 You have abunch of if statements to get the index when all you need to do is use the number generated.
当您需要做的就是使用生成的数字时,您有大量的 if 语句来获取索引。
var palindromeArray = ["racecar", "noon", "mom", "tenet", "sagas", "hill", "programs", "computer", "internet"]; const palindromeGenerator = () => { const random = Math.floor(Math.random() * palindromeArray.length); return palindromeArray[random]; } var pal = palindromeGenerator(); console.log(pal)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.