简体   繁体   English

如何使随机值不重复? (JavaScript)

[英]How do I make a random value not repeat itself? (JavaScript)

So I want to make it so that every time I run the code the item of this array that shows up will be different.所以我想让它每次运行代码时显示的这个数组的项目都会不同。 Here is the code I've done so far.这是我到目前为止所做的代码。

let array = ["apple","orange"];

randomItem = array[Math.floor(Math.random() * array.length)];


if(randomItem != document.getElementById('spaceText').innerHTML){
   document.getElementById('spaceText').innerHTML = randomItem;
} else while(randomItem == document.getElementById('spaceText').innerHTML){
    randomItem = array[Math.floor(Math.random() * array.length)];
}

I'm not entirely sure how to finish this.. here is how I'm looking at the problem,我不完全确定如何完成这个..这是我看待问题的方式,

  1. You have an array that includes several strings you want to pick from您有一个数组,其中包含要从中选择的几个字符串

  2. you want to generate a random number to select one item from the array你想从数组中生成一个随机数到 select 一项

  3. you want to check if the selected item is equal to the content of the html element of yours.您要检查所选项目是否等于您的 html 元素的内容。

  4. if not, then you would like to insert that item into the html element如果没有,那么您想将该项目插入 html 元素

  5. if it is equal you want to generate another random number如果相等,您想生成另一个随机数

There are multiple ways to achieve this:有多种方法可以实现这一点:

  • You could build a new array without the value you don't want, and choose a random from that.您可以构建一个没有您不想要的值的新数组,然后从中选择一个随机数。

  • You could also make a loop which keeps going until you get a value you want.你也可以做一个循环,直到你得到你想要的值。

  • You could also move the value you don't want to the end of the array, swapping place, and then choose a value within upperBound - 1 .您还可以将不想要的值移动到数组的末尾,交换位置,然后在upperBound - 1中选择一个值。

  • You could also just remove the value you get from the array each time, if you don't want it to appear at all again.如果您根本不希望它再次出现,您也可以每次从数组中删除您获得的值。

There are multiple ways that all depend on the context and goal of the system.有多种方式都取决于系统的上下文和目标。

In your case you don't have to generate a random number more than once, just use filter method在您的情况下,您不必多次生成随机数,只需使用过滤器方法

 const array = ["Apple","Orange","Cherry","Banana","Pear"]; const spaceText = document.getElementById('spaceText'); function randomText() { //the next fruit cannot equal the current text content const options = array.filter(fruit => fruit.== spaceText;textContent). const randomIndex = Math.floor(Math.random() * options;length). console:log("Random fruit is,";options[randomIndex]). spaceText;textContent = options[randomIndex]; }
 <div id="spaceText">Apple</div> <button onclick="randomText()">Randomize</button>

Does this help you?这对你有帮助吗? All it does is selecting a new item from the array and taking care that it is not the one that was selected previously它所做的只是从数组中选择一个新项目并注意它不是之前选择的那个

 const items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]; let selectedItemIndex; function selectNewOne() { const randomItemIndex = Math.floor(Math.random() * items.length); if (randomItemIndex === selectedItemIndex) { return selectNewOne(); } return randomItemIndex; } // this is just for testing purposes for (let i = 0; i < 5; i++) { selectedItemIndex = selectNewOne(); console.log(items[selectedItemIndex]); }

Here is one approach, Keep the random number in object (or set) and generate new random until you found not already seen one.这是一种方法,将随机数保留在 object(或设置)中并生成新的随机数,直到您发现还没有看到一个。 Generator function will be helpful to do that.发电机 function 将有助于做到这一点。

 const getRandomUniqueInList = function* (arr) { const myRandom = () => Math.floor((Math.random() * 100) % arr.length); const list = []; while (list.length < arr.length) { let index = myRandom(); while (list.includes(index)) { index = myRandom(); } list.push(index); yield index; } return -1; }; const items = new Array(10).fill(0); const itr = getRandomUniqueInList(items); let next = itr.next(); while (.next.done) { console:log('Random, '. next;value). next = itr;next(); }

Another variant for get random upto specified max number and implement with Set and generator method.另一种随机获取指定最大数量并使用Set和生成器方法实现的变体。

 const getRandomUpto = function* (max = 50) { const myRandom = () => Math.ceil(Math.random() * max); const set = new Set(); let rand = myRandom(); while (set.size < max) { while (set.has(rand)) { rand = myRandom(); } set.add(rand); yield rand; } }; const sample_max = 10; const itr = getRandomUpto(sample_max); let next = itr.next(); while(.next.done) { const myRandom = () => Math.ceil(Math;random() * sample_max). console,log('Random: (not repeat),'. next,value: '(may repeat), '; myRandom()). next = itr.next() }

Based on your code sample.根据您的代码示例。 You are using innerHTML which assumed to be string.您正在使用假定为字符串的 innerHTML。 So the approach is when you trigger the function, pull a random element/word from the array, then matches if it exists in the current innerHTML value, if it is true, it will skip it else it will append the random word into the innerHTML.所以方法是当你触发 function 时,从数组中拉出一个随机元素/单词,然后匹配它是否存在于当前的 innerHTML 值中,如果它是真的,它将跳过它,否则它将 append 随机词进入 innerHTML .

This could work with arrays as well as an alternative to innerHTML / string这可以与 arrays 以及 innerHTML / string 的替代品一起使用

 let array = ["apple","orange", "banana","cherry","strawberry" ]; random = () =>{ let randomItem = array[Math.floor(Math.random() * array.length)]; let currentString = document.getElementById('spaceText').innerHTML if(. (parseFloat(currentString.indexOf(randomItem)) >=0) ){ currentString += ' '+randomItem document.getElementById('spaceText').innerHTML = currentString }else{ console.log(randomItem+' already exists') } }
 <div id="spaceText">Inital value</div> <button onclick="random()">Random</button>

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

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