首页 > 解决方案 > 使用 math.random 函数的多个输出

问题描述

因此,我使用此代码发送一条消息,该消息将聊天中发送的表情随机化(不和谐),但我想这样做,因此当发送表情时,每个表情都是不同的。例如,如果用户要发送它会发送的命令:1、2、3、4、2、3 等。我怎样才能使每个表情都不同。我发现的唯一方法是让每个表情都有不同的 var math.random 函数。这是任何其他方式,因为制作不同的 var 有点长。

const randomemote = [
  `:four:`,
  `:one:`,
  `:two:`,
  `:three:`
];
var emotes = randomemote[Math.floor(Math.random()*randomemote.length)];
message.channel.send(`
  ${emotes}${emotes}${emotes}${emotes}${emotes}
  ${emotes}${emotes}${emotes}${emotes}${emotes}
  ${emotes}${emotes}${emotes}${emotes}${emotes}
  ${emotes}${emotes}${emotes}${emotes}${emotes}
  ${emotes}${emotes}${emotes}${emotes}${emotes}
  `)

标签: javascript

解决方案


创建一个函数,在给定重复次数的情况下,该函数会产生多次随机表情。

const randomemote = [
  `:four:`,
  `:one:`,
  `:two:`,
  `:three:`
];
const randEmote = () => randomemote[Math.floor(Math.random()*randomemote.length)];
const multRandEmotes = count => Array.from({ length: count }, randEmote)
  .join('');
const strToSend = `
  ${multRandEmotes(5)}
  ${multRandEmotes(5)}
  ${multRandEmotes(5)}
  ${multRandEmotes(5)}
  ${multRandEmotes(5)}
  `;
console.log(strToSend);

您还可以创建另一个函数,根据要打印的行数和每行的表情数,multRandEmotes多次调用:

const randomemote = [
  `:four:`,
  `:one:`,
  `:two:`,
  `:three:`
];
const randEmote = () => randomemote[Math.floor(Math.random()*randomemote.length)];
const multRandEmotes = count => Array.from({ length: count }, randEmote)
  .join('');
const multiLineEmotes = (lines, count) => `
  ${
    Array.from({ length: lines }, () => multRandEmotes(count))
    .join('\n  ')}
  `;
console.log(multiLineEmotes(5, 5));
console.log(multiLineEmotes(2, 7));


推荐阅读