<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
</body>
<script>
//1.數組升序排序
var arr1 = [6,11,22,3,1,55];
function fnSortAsc(array){
var temp;
for (var i = 0; i < array.length -1; i++) {
for (var j = array.length - 1; j > i ; j--) {
if (array[j] < array[i]) {
temp = array[j];
array[j] = array[j-1];
array[j-1] = temp;
}
}
}
}
fnSortAsc(arr1);
console.log('升序排序數組:' + arr1);
//2.計算數組的平均值
var arr2 = [22,1,3,4,5,6,7,66,77];
function fnAverage(array){
var sum =0;
for (let index = 0; index < array.length; index++) {
sum += array[index];
}
return sum * 1.0 / array.length;
}
console.log('數組平均值:' + fnAverage(arr2));
//3.求數組中的最大值
var arr3 = [22,1,3,4,5,6,7,66,77];
function fnMax(array){
var max =array[0];
for (let index = 1; index < array.length; index++) {
if (array[index] > max) {
max = array[index];
}
}
return max;
}
console.log('數組最大值:' + fnMax(arr3));
//4.將數組轉換成用“|”隔開的字符串,不可使用內置函數Join()
var arr4 = ['儒','釋','道'];
function fnJoin(array , separator){
var strResult = '';
for (let index = 0; index < array.length; index++) {
strResult += array[index] + separator;
}
strResult = strResult.substring(0 , strResult.length - 1);
return strResult;
}
console.log('數組拼接值:' + fnJoin(arr4 , '|'));
//5.將數組的元素的順序進行反轉,不可使用內置函數reverse()
var arr5 = ['3','儒','2','釋','1','道'];
function fnReverse(array){
var temp = '';
for (var index = 0; index < array.length / 2; index++) {
temp = array[index];
array[index] = array[array.length - 1 - index];
array[array.length - 1 - index] = temp;
}
}
fnReverse(arr5);
console.log('數組反轉:' + arr5);
//6.數組的Sort()方法
var arr6 = ['Kobe' , 'James' , 'Jordan' , 'Yao', 'Panshengzhi'];
arr6.sort();
//字符串數組排序是ASCII字母碼值排序
console.log('升序' + arr6);
//降序排序
arr6.reverse();
console.log('降序' + arr6);
var arr7= [1,2,3,4,5,6,7,8,11,22,33,44,566,777];
arr7.sort();
console.log('整數數組排序' + arr7);
//將數組的內容按照數字的方式排序
arr7.sort(function(x, y){ return x- y ;})
console.log('整數數組排序' + arr7);
</script>
</html>