Javascript Weighted Probability Array

前端 未结 1 909
深忆病人
深忆病人 2021-01-23 09:43

I\'m working on a very basic game which runs in the browser. When the document is ready, I have created some Javascript which displays a random couple of links from a larger lin

相关标签:
1条回答
  • 2021-01-23 10:21

    this is a more neat version:

    $(document).ready(function(){
     var totalArray = [];
        $('#stackoverflow').children().each(function(){
        totalArray.push($(this)):
        });
    
        function randomChoice(){
            var randomNumber=Math.floor(Math.random()*3)+Math.floor(Math.random()*3); //middle buttons have more chance of apearing
            return randomNumber;
        };
    
        var selectedArray = [totalArray[(randomChoice()], totalArray[randomChoice()]];
        $.each(selectedArray,function(index,object){
           $(object).show();
        }
    
    });
    

    even shorter code:

    function randomChoice(){
        var randomNumber=Math.floor(Math.random()*3)+Math.floor(Math.random()*3); //middle buttons have more chance of apearing
        return randomNumber;
    };
    
    $('#button'+ randomChoice()).show():
    $('#button'+ randomChoice()).show():
    

    for probability you could set html data attribute:

    <a href="nextpage.html" id="button1" class="button" data-change="20">Next Page 1</a>
    .. means 20% change of apearing
    
    
    var total = 0;
    $('#stackoverflow').children().each(function(){
        totalArray.push($(this)):
        if($(this).data('change')>Math.random()*100){
          $(this).show();
        }
        });
    
    0 讨论(0)
提交回复
热议问题