随机读取数组中n个元素

需求

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

分析

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

实现

实现代码
<template>
  <div class="container">
    <div class="container-div">
      <img v-for="item in randomList" :key="item" :src="item" />
    </div>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      imgList: [], //所有图片路径列表
      randomList: [], //随机图片路径列表
    };
  },
  mounted() {
    this.getImgList();
  },
  methods: {
    //获取所有图片列表
    getImgList() {
      let path = "";
      for (let i = 1; i < 16; i++) {
        path = "./img/randomList/" + i.toString() + ".jpg";
        this.imgList.push(path);
        path = "";
      }
      this.getRandomList(this.imgList, 5);
    },

    //从数组中随机获取一个元素
    // var ele = arr[Math.floor(Math.random()*arr.length)];

    //获取随机图片列表
    getRandomList(arr, count) {
      var shuffled = arr.slice(0),
        i = arr.length,
        min = i - count,
        temp,
        index;
      while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
      }
      this.randomList = shuffled.slice(min);
    },
  },
};
</script>
<style scoped>
.container-div {
  text-align: center;
  margin: 30px 0px;
}
.container-div img {
  width: 350px;
  height: 200px;
}
</style>

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

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

posted @ 2022-03-02 17:27  曦12  阅读(67)  评论(0编辑  收藏  举报