newarr为新数组,arr为原数组
1.先打乱原数组,然后逐个输出。
var newarr = arr.sort(function(){ return 0.5 - Math.random(); });
2.while方法。
var arr = ["饼山地车播放","纪委发出","我解方程","我碰见欧迪芬","我就开始对","我文件而发愁"]
var newarrNum = 2;
var hash = {};
var newarr = [];
while(newarrNum>0){
var ran = rd(0,arr.length-1);//随机
if(!hash[ran]){
hash[ran] = 1;
newarr.push(arr[ran]);
newarrNum--;
}
}
function rd(n, m) {
var c = m - n + 1;
return Math.floor(Math.random() * c + n);
}