1、2种方案代码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>javascript洗牌(乱序)算法</title>
</head>
<body>
<script>
//方法一
var arr = [1, 2, 3, 4, 5, 6];
function sort(arr) {
var newArr = [];
for(var i = 0, len = arr.length; i < len; i++) {
var j = Math.floor(Math.random() * (len - i));
newArr[i] = arr[j];
arr.splice(j, 1)
}
return newArr;
}
//方法二
function sort2(arr) {
var newArr = [];
newArr = arr.sort(function() {
return Math.random() - 0.5;
})
return newArr;
}
console.log(sort(arr))
console.log(sort2(arr))
</script>
</body>
</html>
2、说明
方法一时间复杂度:O(n)
方法二时间复杂度:O(n²)