JavaScript面试题-数组中最大差值

JavaScript面试题-数组中最大差值

1、forEach

let arr = [23, 4, 5, 2, 4, 5, 6, 6, 71, -3];
const difference = arr => {
    
    
    let min = arr[0],
        max = 0;
    arr.forEach(value => {
    
    
        if (value < min) min = value
        if (value > max) max = value
    })
    return max - min ;
}
console.log(difference(arr))  // 74

2、max、min

let arr = [23, 4, 5, 2, 4, 5, 6, 6, 71, -3];
const difference = arr => {
    
    
    let max = Math.max(...arr),
        min = Math.min(...arr);
    return max - min ;
}
console.log(difference(arr)) // 74

*陆荣涛前端学习交流Q群858752519
加群备注:CSDN推荐

请添加图片描述

猜你喜欢

转载自blog.csdn.net/sdasadasds/article/details/125386541
今日推荐