没有重复的随机报价生成器

时间:2018-11-11 16:21:57

标签: javascript

我开始使用Javascript,并且大约是初学者,我找到了这个随机报价生成器,但是试图弄清楚如何制作它,因此它不会重复其中的任何一个,因为我最终想添加一个庞大的列表的引号,它不会重复出现。

var Quotation=new Array() 

Quotation[0] = "Time is of the essence! Comb your hair.";
Quotation[1] = "Sanity is a golden apple with no shoelaces.";
Quotation[2] = "Repent! The end is coming, $9.95 at Amazon.";
Quotation[3] = "Honesty blurts where deception sneezes.";
Quotation[4] = "Pastry satisfies where art is unavailable.";
Quotation[5] = "Delete not, lest you, too, be deleted.";
Quotation[6] = "O! Youth! What a pain in the backside.";
Quotation[7] = "Wishes are like goldfish with propellors.";
Quotation[8] = "Love the river's \"beauty\", but live on a hill.";
Quotation[9] = "Invention is the mother of too many useless toys.";

var Q = Quotation.length;
var whichQuotation=Math.round(Math.random()*(Q-1));
function showQuotation(){document.write(Quotation[whichQuotation]);}
showQuotation();

2 个答案:

答案 0 :(得分:0)

一种方法是从可用池中删除报价。

var Q = Quotation.length;
var whichQuotation=Math.round(Math.random()*(Q-1));
function showQuotation(){document.write(Quotation[whichQuotation]);}
showQuotation();
Quotation.splice(whichQuotation, 1); //<-- this is how we remove it from the array

splice()允许我们更改数组的内容,包括删除元素。

传递的第一个参数表示我们要开始删除的(数组元素的)索引。第二个参数表示从该点删除多少个元素。

另一种方式是:

delete Quotation[whichQuotation];
Quotation = Array.filter(val => val);

第一行删除数组元素,但保留其空白位置。然后,我们通过在数组上运行一个简单的过滤器来收集数组中剩余的非空元素,该过滤器将只保留那些不为空的插槽。

答案 1 :(得分:0)

您可以存储已经被永久使用的引号的索引(这样它们就可以在页面重新加载后继续存在),生成一个新索引,直到找到一个不再重复的引号为止。

  // helper to store arrays persistently
  function getArray(name) {
    return JSON.parse(localStorage.getItem(name)) || [];
  }

  function storeArray(name, indices) {
    localStorage.setItem(name, JSON.stringify(indices));
  }


  function getNonRepeating(name, array) {
     let used = getArray(name);
     // All quotes were shown already, restart
     if(used.length == array.length)
       used = [];

     // Generate a new index as long as it is already used
     let index;
     do {
       index = Math.floor( Math.random() * array.length );
     } while(used.includes(index))

     // Add the index to the used ones:
     used.push(index);
     // Store them:
     storeArray(name, used);

     return array[index];
 }

 // Array literals make the code much more readable:
 const quotes = [
   "a",
   "b",
   "c"
 ];

 // document.write() is deprecated, instead manipulate the DOM:
 document.body.textContent = getNonRepeating("quote", quotes);