求数组最值的几种方法

156 阅读1分钟
//求数组最大值的四种方法,最小值同理
//sort排序:
console.log(ary.sort((a, b) => b - a)[0]);
//循环法:
function aryMax(n) {
    //设置初始值;
    let Max = 0;
    //遍历数组每一项;
    n.forEach(item => item > Max ? Max = item : null);
    //返回值为最大值;
    return Max
};
console.log(aryMax(ary));
// Math法:
console.log(Math.max(...ary));
// apply方法:
console.log(Math.max.apply(null, ary));