每天在JS或jquery中获取一个新的随机数

时间:2017-02-06 14:08:06

标签: javascript jquery math logic

我正在构建一个当天的笑话迷你app并且无法安静地弄清楚如何每天生成一个新的随机数。随机数指向json中的一个笑话。我有随机数部分工作,但我只需要它在新的一天随机化,而不是每个浏览器刷新。

这是我到目前为止所得到的

<script>
            $(document).ready(function () {
                $.getJSON('js/jokes.json', function (data) {
                    var randomJoke = (Math.floor(Math.random() * data.OneLiners.length));
                    var newJoke = randomJoke;
                    var decide = (Math.floor(Math.random() * 2));
                    var jokeofDay = data.OneLiners[newJoke].joke;
                    var riddleofDay = data.Riddles[newJoke].Question;
                    var riddleAnswer = data.Riddles[newJoke].Answer;
                    var riddle = "Question: " + riddleofDay + "<br/> Answer: " + riddleAnswer;
                    if (decide == 0) {
                        document.getElementById("JoD").innerHTML = jokeofDay + " ";
                    } else {
                        document.getElementById("JoD").innerHTML = riddle;
                    }
                });
            });

                if(jQuery) console.log('jQuery is loaded.');
        </script>

2 个答案:

答案 0 :(得分:1)

您最好的选择是将值存储在具有到期时间的Cookie中。这样您就可以将其留给浏览器来判断笑话ID是否已过期。这是一个纯粹的JS示例,说明了如何做到这一点:

// Will return a joke id between the min and max values. Once the joke ID has 
// been generated for the day, it is persisted in a cookie until midnight.
function getJokeId(minId, maxId) {
  var jokeId = getCookie('joke');

  if (jokeId !== null) {
    return jokeId;
  }

  var expire = new Date();
  expire.setHours(23,59,59,0);

  jokeId = Math.floor(Math.random()*(maxId - minId + 1) + minId);

  document.cookie = 'joke='+jokeId+';expires='+expire.toGMTString()+';path=/';

  return jokeId;
}


// Just a helper function for accessing cookies in JS - could be replaced with 
// jQuery plugin or similar if needed.
function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");

  if (parts.length == 2) {
    console.log('Found joke ID from cookie');
    return parts.pop().split(";").shift();
  }

  console.log('No joke ID found - new one needed');
  return null;
}

getJokeId(0, 5);

以下是示例代码的JS小提琴:https://jsfiddle.net/edcs/0Lpg9ro6/

答案 1 :(得分:0)

如果每个用户都可以获得自己的随机值,但是每天只更改一次,请使用Cookie或.localStorage来记住自上次获得新值以来的持续时间。< / p>

否则,您必须实现自己的随机数生成器。内置的JS不允许您指定自己的“种子”。

来自MDN

  

实现选择初始种子到随机数生成算法;它不能被用户选择或重置。