The JavaScript is a very versatile language and it has a function almost everything that you want.
JavaScript是一種非常通用的語言,它幾乎具有您想要的所有功能。
Here, we will show you how to generate random unique elements from an array in JavaScript?
在這里,我們將向您展示如何從JavaScript數組中生成隨機的唯一元素?
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()函數可以為您完成此工作。 它是一個強大的功能,可以生成多個隨機唯一數 。 random()函數生成一個介于o和1之間的浮點數。僅包含1。因此,我們將使用此隨機數查找JavaScript數組的隨機元素。
JavaScript code to get multiple random unique elements from an array
JavaScript代碼從數組中獲取多個隨機唯一元素
<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:
說明:
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.
該程序找到隨機數,然后使用數組的索引來獲取數組的元素,然后顯示內容。 這里的內容是帶有索引號的鏈接。
翻譯自: https://www.includehelp.com/code-snippets/how-to-get-multiple-random-unique-elements-from-an-array-in-javascript.aspx