方法1-使用Math.min()、Math.max()配合apply
var arr = [11, 23, 32, 4, 5, 7, 9, 76, 8, 9, 4, 34, 25, 43, 22];
var max = Math.max.apply(null, arr);
var min = Math.min.apply(null, arr);
console.log(arr);
console.log('这组数字的最大值是' + max + ',最小值是' + min);
方法2-循环遍历
var arr = [11, 23, 32, 4, 5, 7, 9, 76, 8, 9, 4, 34, 25, 43, 22];
var max = arr[0];
var min = arr[0];
for (var i = 1; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i];
} else if (min > arr[i]) {
min = arr[i];
}
}
console.log(arr);
console.log('这组数字的最大值是' + max + ',最小值是' + min);
方法3-sort()排序 取首尾部项
var arr = [11, 23, 32, 4, 5, 7, 9, 76, 8, 9, 4, 34, 25, 43, 22];
arr.sort(function fun(a, b) {
// 降序
return a - b;
})
console.log(arr);
var max = arr[arr.length - 1];
var min = arr[0];
console.log('这组数字的最大值是' + max + ',最小值是' + min);
方法4-降序或者升序排列,之后取首尾部
var arr = [11, 23, 32, 4, 5, 7, 9, 76, 8, 9, 4, 34, 25, 43, 22];
for (var m = 1; m <= arr.length; m++) {
for (var n = arr.length - 1; n >= m; n--)
if (arr[n] > arr[n - 1]) {
var p = arr[n - 1];
arr[n - 1] = arr[n];
arr[n] = p
}
}
console.log('这组数字的最大值是' + arr[0] + ',最小值是' + arr[arr.length - 1]);
//这组数字的最大值是76,最小值是4