简体   繁体   中英

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.

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.

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.

 <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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