2013-05-01 46 views
1

我正在研究一个在浏览器中运行的非常基础的游戏。当文档准备就绪时,我创建了一些Javascript,它从一个更大的链接列表中显示一对随机的链接(这两个列表都存储在数组中)。我的问题有两个部分 - 一个简单,一个复杂:Javascript加权概率数组

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

使用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(); 

}); 

任何想法/想法都会受到感谢。

这是我在这里的第一篇文章...请温柔!

回答

0

这是一个更整洁的版本:

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

非常感谢您!这非常有用......并且更加优雅。 – 2013-05-03 09:44:50