简体   繁体   English

如何在 JavaScript 中获取随机列表项

[英]How to get a random list item in JavaScript

I am using discord.py to make a Discord bot that gives you a complement every 24 hours.我正在使用 discord.py 制作一个 Discord 机器人,每 24 小时为您提供一次补充。 To test, I set the timer to 1 second.为了测试,我将计时器设置为 1 秒。 The code I made looked like this:我制作的代码如下所示:

const Discord = require('discord.js')
const client = new Discord.Client()

const complements = [
    ...
]

client.once('ready', () => {
    console.log('Logged in!');
    client.user.setActivity("with nice complements.")
    setInterval(console.log,1000,complements[Math.floor(Math.random() * (complements.length - 1))]);
});

However, this just returns the same complement every time.但是,这只是每次都返回相同的补码。 Is there any ways it can choose a random complement?有什么方法可以选择随机补码?

The parameters you pass to setInterval are evaluated at the time when you pass them to the setInterval function not at each execution of it.您传递给setInterval的参数在您将它们传递给setInterval function 时进行评估,而不是在每次执行时进行评估。

So this: setInterval(console.log,1000,complements[Math.floor(Math.random() * (complements.length - 1))]);所以这个: setInterval(console.log,1000,complements[Math.floor(Math.random() * (complements.length - 1))]);

is equal to:等于:

let complement = complements[Math.floor(Math.random() * (complements.length - 1))];
setInterval(console.log,1000, complement);

You need to pass a callbnack function to setInterval that is executed, and move you random access there.您需要将 callbnack function 传递给执行的setInterval ,然后将您随机访问那里。

setInterval(() => {
   console.log(complements[Math.floor(Math.random() * (complements.length - 1))])
}, 1000)

Try to use setInterval like this:尝试像这样使用setInterval

setInterval(() => {
  const value = complements[Math.floor(Math.random() * (complements.length - 1))];
  console.log(value);
},1000);

Rather than pass a fixed argument to console.log in each iteration (I'd actually never seen setInterval called with more than 2 parameters before and had to look up what it meant:-)), pass a function which, when called, generates a new random value and passes that to console.log :与其在每次迭代中向console.log传递一个固定参数(实际上我之前从未见过setInterval调用超过 2 个参数并且不得不查找它的含义:-)),而是传递一个 function ,它在调用时会生成一个新的随机值并将其传递给console.log

 setInterval(() => {
    const complement = complements[Math.floor(Math.random() * (complements.length - 1)) ] ;
    console.log(complement);
 }, 1000)

Problem is setInterval.问题是setInterval。 He call the function with the same result.他调用 function 得到相同的结果。 Try it and check console试试看并检查控制台

 let x = setInterval(console.log(Math.random()),1000,); let num = 0; let y = setInterval(() => { console.log(num) num += 1 },1000,);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM