因为要做一个随机文章的内容,所以需要从后台传回的数据中随机读取几个数据,找到了下面的办法。
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
暂无评论内容