簡體   English   中英

Javascript加權概率數組

[英]Javascript Weighted Probability Array

我正在開發一個在瀏覽器中運行的非常基本的游戲。 准備好文檔后,我創建了一些Javascript,該JavaScript顯示了來自較大鏈接列表的隨機鏈接(兩個列表均存儲在Array中)。 我的問題分為兩個部分-一個簡單,一個復雜:

1)有沒有一種方法可以使此代碼更優雅-數組中數組內的函數非常難看...

2)有沒有一種方法可以將概率分配給項目,以使某些概率比其他概率更高? 目前,這只是隨機的,任何“按鈕”都可能像其他任何按鈕一樣出現。

這是我的代碼:

的HTML

<body>

<h1 id="OTM_Test">Javascript Probability</h1>

<div id="stackoverflow">

<a href="nextpage.html" id="button1" class="button">Next Page 1</a>
<a href="nextpage.html" id="button2" class="button">Next Page 2</a>
<a href="nextpage.html" id="button3" class="button">Next Page 3</a>
<a href="nextpage.html" id="button4" class="button">Next Page 4</a>
<a href="nextpage.html" id="button5" class="button">Next Page 5</a>
<a href="nextpage.html" id="button6" class="button">Next Page 6</a>

</div>

</body>

CSS .button{ background:blue; color:white; display:none; margin:200px; padding:10px; display:none; border:2px solid red; } .button{ background:blue; color:white; display:none; margin:200px; padding:10px; display:none; border:2px solid red; }

Javascript / jQuery

$(document).ready(function(){

var button1 = $("#button1");
var button2 = $("#button2");
var button3 = $("#button3");
var button4 = $("#button4");
var button5 = $("#button5");
var button6 = $("#button6");

var totalArray = [button1,button2,button3,button4,button5,button6];



function randomChoice(){
    var randomNumber=Math.floor(Math.random()*6);
    return randomNumber;
    };



var selectedArray = [(totalArray[(randomChoice())]), (totalArray[(randomChoice())])];

function reduceArray(){
    for(i=0;i<selectedArray.length;i++){
        (selectedArray[i]).show();
        }
};

reduceArray();

});

任何想法/想法將不勝感激。

這是我在這里的第一篇文章...請保持溫柔!

這是一個更簡潔的版本:

$(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();
    }

});

甚至更短的代碼:

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():

為了概率,您可以設置html數據屬性:

<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();
    }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM