vue从一个数组中随机读取5条数据存储在另一个数组中

因为要做一个随机文章的内容,所以需要从后台传回的数据中随机读取几个数据,找到了下面的办法。

  methods:{
    /* 随机获取数组中的数据*/
    getRandomArrayElements(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;
      }
      return shuffled.slice(min);
    },
    /*从数组中随机读取*/
    getRandomNum(){
      this.randomArticles = this.getRandomArrayElements(this.articleRes.contents,5);
      console.log(this.randomArticles);
    },
    /*获取需要处理的数组*/
    listArticles(){
      api.listArticle(this.page,this.size).then(res =>{
        if (res.code === api.SUCCESS_CODE){
          this.articleRes = res.data;
        }
      })
    }
  },

index = Math.floor((i + 1) * Math.random());这是向下取整的随机数取法,会生成1~i之间的数字。

© 版权声明
THE END
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容