Get random element from array, display it, and loop - but never followed by the same element

后端 未结 3 1184
一生所求
一生所求 2021-01-24 08:48

I wrote a simple enough randomize function that loops through the elements in an array and displays them one after the other.

See it here.

function chang         


        
3条回答
  •  滥情空心
    2021-01-24 09:10

    Stop upvoting please :-D

    The following answer is better: https://stackoverflow.com/a/32395535/1636522. The extended discussion between me and Tim enlighten on why you should avoid using my solutions. My answer is only interesting from this point of view, hence, it does not deserve any upvote :-D


    You could save the last integer and "while" until the next one is different:

    var i, j, n = 10;
    setInterval(function () {
      while ((j = Math.floor(Math.random() * n)) === i);
      document.write(j + ' ');
      i = j;
    }, 1000);

    Or even simpler, just add 1... :-D Modulo n to prevent index overflow:

    var i, j, n = 10;
    setInterval(function () {
      j = Math.floor(Math.random() * n);
      if (j === i) j = (j + 1) % n;
      document.write(j + ' ');
      i = j;
    }, 1000);

    First solution applied to your code:

    var whatAmI = ["Webdesigner", "Drummer", "Techie", "Linguistics student", "Photographer", "Geek", "Coder", "Belgian", "Batman", "Musician", "StackExchanger", "AI student"];
    var j;
    var i = 1; // since you start with "Drummer"
    var n = whatAmI.length;
    
    function changeSubTitle() {
      setTimeout(function () {
        while ((j = Math.floor(Math.random() * n)) === i);
        $(".page-header > h2").animate({
          "opacity": 0
        }, 700, function () {
          $(this).text(whatAmI[j]);
          $(this).animate({
            "opacity": 1
          }, 700, changeSubTitle);
        });
      }, 1000);
      i = j;
    }
    
    changeSubTitle();
    
    

提交回复
热议问题