每次获得不同的随机值

时间:2016-09-18 16:03:23

标签: javascript jquery algorithm sorting

我被困在某事上。我希望用户能够从数组中选择一个值。但挑战在于他/她无法获得与之前相同的价值。

https://jsbin.com/hibihubega/edit?html,js,console,output

我不知道如何继续,帮助。

function getNum(){
  var num = ['1', '2', '3', '4', '5'];

var selected = num[Math.floor(Math.random() * num.length)];
var history = selected;

  if(history){

  }

}

$('button').click(function(){
  console.log(getNum());
})

3 个答案:

答案 0 :(得分:1)

试试这个:

$(document).ready(function() {

     num = ['1', '2', '3', '4', '5'];
     temp =[];

    $("button").on("click",function(){

        getNum();

    })

    function getNum(){

        if ( num.length <= 0  ) {
            num = temp;
            temp =[];  
        }

        var indexRandom = Math.floor(Math.random()*(num.length));
        console.log(num[indexRandom]);
        temp.push(num[indexRandom]);
        num.splice(indexRandom,1);
    }

})

最终代码:

&#13;
&#13;
<!DOCTYPE html>
<html>
    <head>
        <style>
        </style>
    </head>
    <body>
 <button>dfdgdfg</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            
$(document).ready(function() {
    
     num = ['1', '2', '3', '4', '5'];
     temp =[];
    
    $("button").on("click",function(){
        
        getNum();
        
    })
    
    function getNum(){
        
        if ( num.length <= 0  ) {
            
            num = temp;
            temp =[];
            
        }
            
             var indexRandom = Math.floor(Math.random()*(num.length));
            console.log(num[indexRandom]);
             temp.push(num[indexRandom]);
             num.splice(indexRandom,1);
    }
            
})
        
            
        </script>
    </body>  
</html>
        
&#13;
&#13;
&#13;

答案 1 :(得分:0)

选择后删除值,并在下一次选择之前替换。

以下是格式化代码的方法:

var num,
    lastNum,
    numbers = [1,2,3,4,5];

function newNum(){
    lastNum && numbers.push(lastNum);
    lastNum = num;
    var r = Math.floor(Math.random() * numbers.length);
    num = numbers[r];
    numbers.splice(r,1);
}

$("button").click(function(){
    newNum();
    console.log(num);
})

拾取的数字是随机的,但绝不是最后选择的数字。

答案 2 :(得分:0)

使用后,只需使用 splice() 删除该值即可。

function getNum() {
    if (num.length==0){
        return false;
    } else {
        var index = Math.floor(Math.random() * num.length)
        var selected = num[index];
        num.splice(index, 1); //remove from array
        return selected;
    }
}

如果你想保存初始值,请创建另一个(克隆)的初始数组并减少它。

相关问题