JS堆栈中不允许有超过4个相同的值

| 因此,我在此函数之后构建了一个JavaScript堆栈:
function Stack()    //Creating Stack Object
    {
    // Create an empty array of cards.
    this.cards = new Array();  //cards array inside stack object
    this.push  = pushdata;      //Call pushdata function on push operation
    this.pop   = popdata;        //Call popdata function on pop operation
    this.printStack = showStackData; //Call showStackData function on printstack operation

    this.populate = function populate() {

            this.push(rand());
            this.push(rand());
            this.push(rand());
            this.push(rand());
        }
    }
(其中rand()只是一个生成0到10之间的随机数的函数-我希望语法是正确的,因为我不得不删除很多注释掉的函数以使其适合本文)。 所以我要实现的是在此堆栈/数组中不允许有4个相同的值。 我发现我可以检查rand()生成的每个数字,然后将其推入堆栈,并向计数器变量添加1,并添加一个条件,以在该计数器的计数器已经为4时不添加此数字。 但这意味着每个可能被压入堆栈的数字都有一个新变量,这对我来说似乎是一个不必要的过大杀伤力,我想您可以理解这不是最优雅的解决方案。 那么您将如何处理呢? 在此先多谢!     
已邀请:
代替
this.push(rand()); 
检查值是否已经在数组中四次
var randNum = rand();
var count = 0;
for(var i = 0; i < this.length; i++){
  if(this[i] === randNum) count++;
}
if(count <= 4) this.push(randNum);
    

要回复问题请先登录注册