javascript - 如何随机选择一个数组?

标签 javascript arrays

我目前正在创建一个游戏,允许用户单击大量图像。根据他们点击的图像,会发生不同的事情。我看过以前的问题,他们似乎都在问“如何随机选择数组中的一个项目”。然而,我的与这些略有不同。抱歉,如果您觉得我的答案在其他地方。但无论如何!

我的问题很简单:

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

//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 负责选择随机数组。

希望你能得到我想要的东西。我已尝试尽可能地进行描述。再次总结一下,我希望能够在游戏开始时选择一个数组,以便可以多次玩游戏。你能写出我需要的代码吗?我有一种感觉,它很简单。但我花了几天时间寻找。

感谢您的帮助:)

最佳答案

创建一个父数组然后引用这个父数组怎么样?

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

您还可以使用 parentArray.push(childArray1); 添加它们,选择更适合您的一个。

关于javascript - 如何随机选择一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10428444/

相关文章:

javascript - 如何用哈希值对这个数组进行排序?

arrays - React 中的过滤器方法在 map 可用时不起作用

arrays - Array[Nothing with java.lang.Object] 在 Scala 2.9.1 中需要

c++ - 遍历未知数量的维度

javascript - 使用 VUE-CLI 的 Node 模块

javascript - ChartJs水平线

javascript - Redux 防止不必要的渲染

javascript嵌套数组

javascript - 表单提交后保留动态表单字段值

javascript - 影响一系列对象