简体   繁体   English

从数组中选择随机文本

[英]Pick Random Text from an Array

I have made it, but is it possible to show it only one time and delete it from the list for each thing?我已经做到了,但是是否可以只显示一次并从每件事的列表中删除它?

For example, it first shows the "first" When it's been sent, I want to send the other 3 messages, and when it's empty, it indicates that there aren't any [answers] in the list.比如它先显示“第一条”发送完后,我要发送其他3条消息,当它为空时表示列表中没有任何[答案]。

const messages = ["first", "two", "three", "four"]
const randomMessage = messages[Math.floor(Math.random() * messages.length) - 1];

I'd suggest using a shuffling algorithm to shuffle your messages, you can then use Array.shift() to pick off messages one by one.我建议使用洗牌算法来洗牌您的消息,然后您可以使用Array.shift()来一一挑选消息。

The shuffle() function here is a basic Fisher–Yates / Knuth shuffle.这里的shuffle()函数是一个基本的Fisher–Yates / Knuth shuffle。

 function shuffle(arr) { for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; } return arr; } const messages = ["first", "two", "three", "four"]; const randomizedMessages = shuffle(messages); let i = 0; // Take messages one by one using Array.pop() while(randomizedMessages.length) { console.log(`Message #${++i}:`, randomizedMessages.shift()); }
 .as-console-wrapper { max-height: 100% !important; top: 0; }

Or using lodash shuffle :或者使用lodash shuffle

 const messages = ["first", "two", "three", "four"]; const randomizedMessages = _.shuffle(messages); let i = 0; while(randomizedMessages.length) { console.log(`Message #${++i}:`, randomizedMessages.shift()); }
 .as-console-wrapper { max-height: 100% !important; top: 0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" referrerpolicy="no-referrer"></script>

After using it, you can find the index of the element picked, then remove it right after.使用后,您可以找到所选元素的索引,然后立即将其删除

const messages = ["first", "two", "three", "four"]
const index = Math.floor(Math.random() * messages.length)
const randomMessage = messages[index]
messages.splice(index, 1)
//rest of what you are going to do with 'randomMessage'

As for checking if it is empty, just check either messages.length or randomMessage .至于检查它是否为空,只需检查messages.lengthrandomMessage Both will be falsy if the array is empty ( messages.length will be 0 and randomMessage will be undefined )如果数组为空,两者都将是的( messages.length将为0并且randomMessage将是undefined

if (!messages.length) console.log("The array is empty!")

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

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