当前位置:主页 > js > 随机读取数组中n个元素

随机读取数组中n个元素

xi5年前 (2020-06-10)js13930

需求

随机不重复的显示一系列图片

分析

可使用Math.random(),其作用是返回介于 0(包含) ~ 1(不包含) 之间的一个随机数。先获取到图片路径,将图片路径放入数组中,再随机从数组中读取n个元素放入新数组,页面只需遍历新数组生成img即可。

实现

  1. <template>
  2. <div class="container">
  3. <div class="container-div">
  4. <img v-for="item in randomList" :key="item" :src="item" />
  5. </div>
  6. </div>
  7. </template>
  8. <script>
  9. export default {
  10. components: {},
  11. data() {
  12. return {
  13. imgList: [], //所有图片路径列表
  14. randomList: [], //随机图片路径列表
  15. };
  16. },
  17. mounted() {
  18. this.getImgList();
  19. },
  20. methods: {
  21. //获取所有图片列表
  22. getImgList() {
  23. let path = "";
  24. for (let i = 1; i < 16; i++) {
  25. path = "./img/randomList/" + i.toString() + ".jpg";
  26. this.imgList.push(path);
  27. path = "";
  28. }
  29. this.getRandomList(this.imgList, 5);
  30. },
  31. //从数组中随机获取一个元素
  32. // var ele = arr[Math.floor(Math.random()*arr.length)];
  33. //获取随机图片列表
  34. getRandomList(arr, count) {
  35. var shuffled = arr.slice(0),
  36. i = arr.length,
  37. min = i - count,
  38. temp,
  39. index;
  40. while (i-- > min) {
  41. index = Math.floor((i + 1) * Math.random());
  42. temp = shuffled[index];
  43. shuffled[index] = shuffled[i];
  44. shuffled[i] = temp;
  45. }
  46. this.randomList = shuffled.slice(min);
  47. },
  48. },
  49. };
  50. </script>
  51. <style scoped>
  52. .container-div {
  53. text-align: center;
  54. margin: 30px 0px;
  55. }
  56. .container-div img {
  57. width: 350px;
  58. height: 200px;
  59. }
  60. </style>

值得注意的是代码中的路径是相对与public下index.html的路径,图片放在src中则访问不到。

页面:

刷新页面后再次随机获取:

转载请标注来源与原作者

本文链接:http://xiblogs.top/?id=10

返回列表

没有更早的文章了...

下一篇:jsonp跨域

“随机读取数组中n个元素” 的相关文章

express项目的创建

express项目的创建

前言前端开发者若要进行后端开发,大多都会选择node.js,在node生态下是有大量框架的,其中最受新手喜爱的便是老牌的express.js,接下来我们就从零创建一个express项目。 安装nod...

js玩儿爬虫

js玩儿爬虫

前言提到爬虫可能大多都会想到python,其实爬虫的实现并不限制任何语言。下面我们就使用js来实现,后端为express,前端为vue3。 实现功能话不多说,先看结果:这是项目链接:https://...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。