Unique random values from array of unique values javascript

前端 未结 2 385
闹比i
闹比i 2021-01-26 22:29

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

2条回答
  •  无人及你
    2021-01-26 23:12

    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.

提交回复
热议问题