简体   繁体   English

即使在页面重新加载后,如何随机生成不重复的数字?

[英]How do I randomly generate non-repeating numbers even after page reload?

Question: How do I generate non-repeating numbers even after page reload?问题:如何在页面重新加载后生成不重复的数字? (Example: 0 -> 100, I would get 10 once, and never again until seeing every other number.) (例如:0 -> 100,我会得到 10 一次,直到看到所有其他数字之前永远不会再得到。)

Preferred Answer: Code block or explanation showing how to generate non-repeating numbers that won't repeat after reloading the page.首选答案:代码块或说明显示如何生成重新加载页面后不会重复的非重复数字。

The easiest way is to save the 'seen' numbers in a form of an object in a cookie or localStorage, for example like that:最简单的方法是在 cookie 或 localStorage 中以对象的形式保存“看到”的数字,例如:

const seenNumbers = {
  51: true,
  64: true
} 

Then every time you load the page, you load this array and try to generate a new number.然后每次加载页面时,都会加载这个数组并尝试生成一个新数字。 Before using it, you check whether it is in seenNumbers and if it is, you try to generate a new one until you get a new number that was not used before.在使用它之前,您检查它是否在seenNumbers ,如果是,则尝试生成一个新号码,直到获得一个以前没有使用过的新号码。 After that, you add it to the seenNumbers and save the cookie.之后,将其添加到seenNumbers并保存 cookie。

Don't forget to have the logic in case of seenNumbers have all the numbers, then your code will try to generate new items forever.不要忘记在seenNumbers拥有所有数字的情况下的逻辑,然后您的代码将尝试永远生成新项目。 To avoid that, first check the number of items in seenNumbers , and if it equals the number of possible numbers, you do not generate any numbers.为避免这种情况,首先检查seenNumbers的项目seenNumbers ,如果它等于可能的数字数,则不生成任何数字。

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

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