您的位置:首页 > Web前端 > JavaScript

如何从JavaScript数组中获取多个随机唯一元素?

2020-08-04 15:53 846 查看

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>
[/code]

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐