从唯一值的数组独特的随机值的JavaScript [英] Unique random values from array of unique values javascript

查看:114
本文介绍了从唯一值的数组独特的随机值的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有十二平方和那些六个是随机选择的,然后应用的样式。这是通过从唯一值的阵列产生的随机值来实现。问题是所产生的随机值不是唯一例如5可以被选择一次以上。我在这里看了那么多帖子上似乎有一些实现这一目标的不同的方式 - 洗牌等,这将是最有效的?

 为(VAR I = 0;我6;;我++)
    (函数(ⅰ){
      的setTimeout(函数(){
        VAR兰特= ARR [Math.floor(的Math.random()* arr.length)];
        VAR平方=的document.getElementById('方'+兰特);
        square.style.background =黑色;
    如果(我== 6)复位();
   },1500 * I)
   })(一世);
   };


解决方案

只是为了简单起见,我会假设你的元素有一个类。

上的jsfiddle示例

所以,我会抓住所有元素:

  VAR元素= document.getElementsByClassName(方);

然后我会创建一个ID的数组

  VAR IDS = [];对于(VAR I = 0; I< elements.length ++ I)
{
    ids.push(元素[I] .getAttribute(ID));
}

和然后在阵列的长度

产生随机数

  VAR随机= roundingFunction(的Math.random()* ids.length);

然后索引检索元素,并从数组中删除

  VAR elementID = ids.splice(随机,1);

和重复。

I have twelve squares and six of those are selected randomly and a style then applied. This is achieved by generating random values from an array of unique values. The problem is the random values being generated aren't unique e.g 5 could be chosen more than once. I've looked at so many posts on here and there seems to be a number of different ways of achieving this - shuffling etc. Which would be the most effective?

   for (var i = 0; i < 6 ; i++)
    (function (i) {
      setTimeout(function () {
        var rand = arr[Math.floor(Math.random() * arr.length)];
        var square = document.getElementById('square' + rand);
        square.style.background = black;
    if (i == 6) Reset();
   }, 1500 * i);
   })(i);
   };

解决方案

Just for the sake of simplicity I will assume your elements have a class.

Example on jsFiddle

So, I would grab all elements:

var elements = document.getElementsByClassName("square");

Then I would create an array with the IDs

var ids = [];

for (var i = 0; i < elements.length; ++i)
{
    ids.push(elements[i].getAttribute("id"));
}

And then generate random numbers on the length of the array

var random = roundingFunction(Math.random() * ids.length);

Then retrieve the element at the index and remove from the array

var elementID = ids.splice(random, 1);

And repeat.

这篇关于从唯一值的数组独特的随机值的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆