简体   繁体   English

如何从 javascript 中没有重复的数组中提取随机字符串?

[英]how to pull random strings from an array with no repeats in javascript?

I'm very new to javascript and working on making a random generator that runs in a browser, and I think I have things mostly figured out, except I can't figure out how to ensure there are no repeats between random strings.我对 javascript 非常陌生,并且正在制作一个在浏览器中运行的随机生成器,我想我已经弄清楚了大部分事情,除了我无法弄清楚如何确保随机字符串之间没有重复。

I was thinking maybe removing the first result from the array so the second can't pick it (preferable, because in the final code there will be multiple variables pulling from the same array in multiple different configurations, and several arrays being pulled from in this way, but I don't know if that's possible?), or maybe having the second one rerun until it gets something unique.我在想也许从数组中删除第一个结果,所以第二个不能选择它(最好,因为在最终代码中,会有多个变量从多个不同配置中的同一个数组中提取,并且从这个中提取了几个 arrays方式,但我不知道这是否可能?),或者可能让第二个重新运行,直到它得到一些独特的东西。

however, I, uh, don't know how to do either of these things, and no amount of googling has given me anything both relevant and understandable enough (as a beginner) for me to successfully apply ^^;但是,我,呃,不知道如何做这两件事,并且没有多少谷歌搜索给我任何相关和足够理解的东西(作为初学者)让我成功申请^^; any help?有什么帮助吗?

this is a simplified version of my code to just include relevant stuff, let me know if I need to provide more这是我的代码的简化版本,仅包含相关内容,如果我需要提供更多内容,请告诉我

 <button onclick="random()">GENERATE</button> <p id="text"></p> <script> var canids = ["dog", "wolf", "coyote", "jackal", "fox", "wild dog", "raccoon dog", "dire wolf", "dingo"] function random() { var canids1 = canids[(Math.random() * canids.length) | 0] var canids2 = canids[(Math.random() * canids.length) | 0] /*i want it to be impossible for this to be the same as canids1*/ document.getElementById('text').innerHTML = canids1 + " " + canids2; } </script>

Here's a basic solution.这是一个基本的解决方案。 You can generate an index of the second candis while it is equal to the first one.您可以生成第二个 candis 的索引,而它等于第一个。

 <button onclick="random()">GENERATE</button> <p id="text"></p> <script> var canids = ["dog", "wolf", "coyote", "jackal", "fox", "wild dog", "raccoon dog", "dire wolf", "dingo"] function random() { var canids_index1 = (Math.random() * canids.length) | 0 var canids_index2 = (Math.random() * canids.length) | 0 while(canids_index1 === canids_index2) canids_index2 = (Math.random() * canids.length) | 0 var canids1 = canids[canids_index1] var canids2 = canids[canids_index2] /*i want it to be impossible for this to be the same as canids1*/ document.getElementById('text').innerHTML = canids1 + " " + canids2; } </script>

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

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