【数组】JS数组随机排序

例:对以下学员随机排序,生成一个新数组:var arr = ["鹿晗","王俊凯","蔡徐坤","彭于晏","周杰伦","刘德华","赵本山"];

function randomSort(arr){
  var newArr = [];
  var length = arr.length;
  for(var i = 1; i <= length; i++){
    //以第一次为例,[0,7),向下取整是避免取到7,原数组索引0~6
    var address = Math.floor(Math.random()*arr.length);
    //原数组去掉已经选中的数组元素,并将其插入到新数组里面
    newArr.push(arr.splice(address,1));
  }
  return newArr;
}
console.log(randomSort(["鹿晗","王俊凯","蔡徐坤","彭于晏","周杰伦","刘德华","赵本山"]));

今日心得: 数组随机排列的方法很多,下次看到更好的方法再补充。

 

你可能感兴趣的:(JS)