Unique random values from array of unique values javascript

前端 未结 2 390
闹比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:25

    There are bascially three different approaches:

    • Pick an item by random and repeat if it was used before.
    • Put all items in an array, pick by random and remove from the array.
    • Put all items in an array and shuffle.

    Which one would be the most efficient can't be answered in the scope of your question. The difference between them is so small that it negligible considering how much the performance differs between browsers.

    If you really need the most efficient, you have to try them all and test the performance in a wide variety of browser.

    Otherwise just pick the one that seems easiest to implement. The are all good enough for any normal application.

提交回复
热议问题