计算整数数组的差值
作者:互联网
方法一
function val(arr) {
let max = Math.max(...arr);
let min = Math.min(...arr);
return max - min
}
let arr = [1, 2, 3, 4, 5, 6];
console.log(val(arr));
方法二
function val(arr) {
arr = arr.sort(function(x , y) {
return x - y;
})
let diff = arr[0] - arr[arr.length - 1];
return diff;
}
let arr = [1, 2, 3, 4, 5, 6];
console.log(Math.abs(val(arr)));
方法三
function val(arr){
let max =Math.max.apply(null,arr);
let min =Math.min.apply(null,arr);
let diff =max-min;
return diff;
}
let arr = [1, 2, 3, 4, 5, 6];
console.log(val(arr));
方法四
function val(arr) {
let max = arr[0],
min = arr[0];
for (let i = 0; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i];
}
if (min > arr[i]) {
min = arr[i];
}
}
return max - min;
}
let arr = [1, 2, 3, 4, 5, 6];
console.log(val(arr));
标签:arr,val,min,max,整数,let,数组,差值,Math 来源: https://www.cnblogs.com/Eamon-18/p/16367411.html