我正在开发一个在浏览器中运行的非常基本的游戏。当文档准备好时,我创建了一些 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
.按钮{
背景:蓝色;
白颜色;
显示:无;
边距:200px;
内边距:10px;
显示:无;
边框:2px 纯红色;
}
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();
}
});
关于Javascript 加权概率数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16318312/