若是多维数组可以通过join和split将其扁平处理后比较
let arr = [1, 2, [1, [1, 2], 2], 3, [1, 2], 4, 50, 5];
let toArr = arr.join(",").split(","); // 转化为一维数组
console.log(toArr);
一、排序法
let arr = [1, 2, 3, 4, 50, 5];
arr.sort((a, b) => a-b );
let max = arr[arr.length - 1];
let min = arr[0];
console.log(max, min);
二、Math 中的 max/min 法
let arr = [1, 2, 3, 4, 50, 5];
let max = Math.max.apply(null, arr);
let min = Math.min.apply(null, arr);
console.log(max, min);
let arr = [1, 2, 3, 4, 50, 5];
let max = Math.max(...arr);
let min = Math.min(...arr);
console.log(max, min);
三、假设法(逐一比较)
let arr = [1, 2, 3, 4, 50, 5];
let max = arr[0];
for( let i = 1; i < arr.length; i ++) {
let current = arr[i];
current > max ? max = current : null;
}
let min = arr[0];
for( let i = 1; i < arr.length; i ++) {
let current = arr[i];
current < min ? min = current : null;
}
console.log(max, min);