可以封装成一个方法,需要时直接调用
methods: {
// arr为需要处理的数组 n为筛选个数
randomArr(arr,n) {
let reslut = [];
for (let i = 0; i < n; i++) {
let random = Math.floor(Math.random() * arr.length);
reslut.push(arr[random]);
arr.splice(random,1);
}
return reslut;
}
}
举个例子
let arr = [{
name:'a'
},{
name:'b'
},{
name:'c'
},{
name:'d'
}]
let resultArr = this.randomArr(arr,3) // 随机筛选3个
console.log(resultArr) // [{name:'a'},{name:'c'},{name:'d'}]