日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

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

發布時間:2023/12/1 javascript 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何从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

輸出量

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

總結

以上是生活随笔為你收集整理的如何从JavaScript数组中获取多个随机唯一元素?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。