如何从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>[/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.
该程序找到随机数,然后使用数组的索引来获取数组的元素,然后显示内容。 这里的内容是带有索引号的链接。
- 如何获取函数传入数组的元素个数——谈数组的退化和引用
- 练习:有一个有序的数组,想要将一个元素插入到该数组中,还要保证该数组是有序的。如何获取该元素在数组中的位置.(2012.2.17)
- JavaScript 随机抽取不重复的数组元素,你真的会吗?
- JavaScript概率游戏抽奖根据cookie判断是否填写资料,从而显示相关的提示;判断元素下标是否在随机生成的数组中,有即让其抽奖
- 如何创建一个随机数组(元素是1到N-1,不重复)
- JavaScript使用slice函数获取数组部分元素的方法
- 笔记(数组的操作&数值的转换&js如何让获取元素并对元素进行操作&link标签的加载解析&border边框)
- JavaScript如何获取一个元素的样式信息
- JavaScript如何获得一个DOM元素的绝对位置?(获取元素位置,不依赖框架)
- JavaScript中数组如何过滤掉相同元素的5种方法
- JavaScript如何获取/计算页面元素的offset?
- Javascript从数组中随机取出不同元素的两种方法
- 对于一个有序的数组,如果要插入一个元素并保证数组还有序, 问如何获取该元素位置。用二分法
- JavaScript——数组(包括:数组的概念、创建数组、获取数组中的元素、遍历数组、获取数组的长度、向数组中新增元素、冒泡排序)
- 如何找出数组中出现次数为奇数次的唯一元素
- javascript如何判断数组内元素是否重复的方法集锦
- javascript 常见数组操作( 1、数组整体元素修改 2、 数组筛选 3、jquery 元素转数组 4、获取两个数组中相同部分或者不同部分 5、数组去重并倒序排序 6、数组排序 7、数组截取slice 8、数组插入、删除splice(需明确位置) 9、数组遍历 10、jQuery根据元素值删除数组元素的方)
- js实现从数组里随机获取元素
- JavaScript数组对象实现增加一个返回随机元素的方法
- JavaScript如何获取数组最大值和最小值