js代码:
function Sort() {
// 定义冒泡排序的方法
this.bubbleSort = function (arr,flag) {
for(var i=0;i<arr.length;i++) {
for(var j=0;j<i;j++) {
if(arr[i]>arr[j]) {
var center = null;// 中间变量用于交换数据
center = arr[i];
arr[i] = arr[j];
arr[j] = center;
center = null;
}
}
}
if(flag == 1) {
// 降序
return arr;
}else {
// 升序
return arr.reverse();
}
}
// 使用数组的排序方法进行排序
this.arrSort = function (arr,flag) {
return arr.sort(function (a,b) {
if(flag == 1) {
// 降序
if(a < b) {
// 如果a<b则a和b交换位置,即数组中大的值放到前面(b大),故是降序。
return 1;
}
}else {
// 升序
if(a > b) {return 1;}
}
});
}
}
html代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>排序</title>
</head>
<body>
</body>
</html>
<script type="text/javascript" src="../js/sort.js"></script>
<script>
var array1 = ["sb","sa","st","sk","si","so","sc"];
var array2 = [7,78,65,12,79,20,15,66];
var array3 = [7,78,65,15,"sa","st","sk",66];
var array4 = ["2018-12-20","2018-12-21","2018-12-19","2018-12-16","2018-12-28"];
var sort = new Sort();
var arr = sort.bubbleSort(array4,1);
console.log(arr)
var arr2 = sort.arrSort(array4,1)
console.log(arr2)
</script>