javascript
如何从JavaScript数组中获取多个随机唯一元素?
The JavaScript is a very versatile language and it has a function almost everything that you want.
JavaScript是一種非常通用的語(yǔ)言,它幾乎具有您想要的所有功能。
Here, we will show you how to generate random unique elements from an array in JavaScript?
在這里,我們將向您展示如何從JavaScript數(shù)組中生成隨機(jī)的唯一元素?
The random() function does this work for you. It is a powerful function that can generate multiple random unique numbers. The random() function generates a float number between o and 1. Including only 1. So, we will use this random number to find random elements of the JavaScript array.
random()函數(shù)可以為您完成此工作。 它是一個(gè)強(qiáng)大的功能,可以生成多個(gè)隨機(jī)唯一數(shù) 。 random()函數(shù)生成一個(gè)介于o和1之間的浮點(diǎn)數(shù)。僅包含1。因此,我們將使用此隨機(jī)數(shù)查找JavaScript數(shù)組的隨機(jī)元素。
JavaScript code to get multiple random unique elements from an array
JavaScript代碼從數(shù)組中獲取多個(gè)隨機(jī)唯一元素
<html><body><div id="one"><p>one</p></div><div id="two"><p>two</p></div><script>function shuffle(a) {for (let i = a.length - 1; i > 0; i--) {const j = Math.floor(Math.random() * (i + 1));[a[i], a[j]] = [a[j], a[i]];}return a;}var arr = ["<span class=\"booklink\"><a href=\"/one\">one</a></span>","<span class=\"booklink\"><a href=\"/one\">two</a></span>","<span class=\"booklink\"><a href=\"/one\">three</a></span>","<span class=\"booklink\"><a href=\"/one\">four</a></span>","<span class=\"booklink\"><a href=\"/one\">five</a></span>"]/* note: the JavaScript that updates the div had to be near the end* of the body to work (probably just after the div)*/shuffle(arr);document.getElementById("one").innerHTML = arr.slice(0, 3).toString();</script></body></html>Output
輸出量
Explanation:
說(shuō)明:
This program finds the random number and then uses the index of the array to fetch elements of the array and then displays the content. Here the content is a link with the index number.
該程序找到隨機(jī)數(shù),然后使用數(shù)組的索引來(lái)獲取數(shù)組的元素,然后顯示內(nèi)容。 這里的內(nèi)容是帶有索引號(hào)的鏈接。
翻譯自: https://www.includehelp.com/code-snippets/how-to-get-multiple-random-unique-elements-from-an-array-in-javascript.aspx
總結(jié)
以上是生活随笔為你收集整理的如何从JavaScript数组中获取多个随机唯一元素?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 这些年那些事剧情介绍
- 下一篇: 自行车多少钱一辆啊?