我目前正在创建一个游戏,允许用户点击大量的图像。根据他们点击的图像,不同的事情会发生。我看过以前的问题,他们似乎都问:“我如何随机选择一个数组内的项目”。但是,我的情况与这些稍有不同。对不起,如果你觉得我的答案在别的地方。但无论如何!如何随机选择一个数组?
我的问题很简单:
如何随机选择一个数组?到目前为止,我的代码包含一个函数,可以检查数组中是否存在整数。这是我的代码到目前为止。
//The array below contains the integers.
example=new Array(1,2,3);
//The function below checks whether 'image' (which is an integer) is the same as any integers within the example array.
function isItThere(obj) {
var j = false;
for (var i = 0; i < example.length; i++) {
if (example[hits] == obj) {
j = true;
break;
}
}
return j;
}
//This is the IF statement I have used. After the integer associated with 'image' has been passed through the 'isItThere' function either A or B will happen. (A happens if the number exists).
if(isItThere(image)){
目前,这一切都工作得很好。当然,这可能不是最有效的方式,但它实现了我迄今为止想要的。
但我现在想要有多个包含整数的数组。这是因为如果用户重新加载游戏,那么他们确切地知道要按下哪些图像来获胜。因此,我想创建几个数组,其中一个数组将在游戏开始时随机选择。
例如..
example0=new Array(1,2,3);
example1=new Array(4,5,6);
example2=new Array(7,8,9);
我相信我应该使用下面的代码。
var num=Math.floor(Math.random()*3);
然后以某种方式将该数字链接到“示例”一词。
这样,我的代码
if(isItThere(image)){
这部分可以保持不变,因为它是一个随机排列的选择交易的isItThere。
希望你得到我想要的东西。我尽量保持描述性。总而言之,我希望能够在游戏开始时选择一个阵列,以便游戏可以多次播放。你能写我需要的代码吗?我有一种感觉很简单。但我花了几天的时间看。
感谢您的帮助:)
创建一个*数组*数组,并选择其中的一个随机。请参阅:[从数组中获取随机值](http://stackoverflow.com/questions/4550505/getting-random-value-from-an-array)。每当你有一个*集合*的东西,使用一个数组或对象来管理它。 –
[Select random function]可能重复(http://stackoverflow.com/questions/9791853/select-random-function) –