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

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

输出量

get multiple random unique elements from an array in JavaScript

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值