2012-05-03 165 views
0

我目前正在创建一个游戏,允许用户点击大量的图像。根据他们点击的图像,不同的事情会发生。我看过以前的问题,他们似乎都问:“我如何随机选择一个数组内的项目”。但是,我的情况与这些稍有不同。对不起,如果你觉得我的答案在别的地方。但无论如何!如何随机选择一个数组?

我的问题很简单:

如何随机选择一个数组?到目前为止,我的代码包含一个函数,可以检查数组中是否存在整数。这是我的代码到目前为止。

//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。

希望你得到我想要的东西。我尽量保持描述性。总而言之,我希望能够在游戏开始时选择一个阵列,以便游戏可以多次播放。你能写我需要的代码吗?我有一种感觉很简单。但我花了几天的时间看。

感谢您的帮助:)

+0

创建一个*数组*数组,并选择其中的一个随机。请参阅:[从数组中获取随机值](http://stackoverflow.com/questions/4550505/getting-random-value-from-an-array)。每当你有一个*集合*的东西,使用一个数组或对象来管理它。 –

+0

[Select random function]可能重复(http://stackoverflow.com/questions/9791853/select-random-function) –

回答

2

如何做父母数组,然后参照这个父阵列?

var childArray1 = [1,2,3], 
childArray2 = [4,5,6], 
childArray3 = [7,8,9], 
parentArray = [childArray1, childArray2, childArray3]; 

您也可以用parentArray.push(childArray1)添加他们。,哪一个更适合你。

+0

你刚刚解决了我的问题!谢谢!所以是的,如果人们现在和我有同样的问题 - 拿Zvonas回答。 – user1371984

0

你应该做一个数组的数组,并选择随机:

var myArray = [ 
    [1, 2, 3], 
    [4, 5, 6], 
    [7, 8, 9], 
]; 

var theArray = myArray[Math.random() * 3)]; 
+0

我不知道我在这里做错了什么。但如果我要用你的答案。我是否正确地将我的代码更改为 函数inArray(obj){var j = false; (var hits = 0; hits user1371984

+0

是的,它应该工作,实际上它与@zvona答案完全相同,但不是有多个childArray,而是直接在家长。而我的'myArray'与@ zvona的'parentArray'完全相同。 –