求一个number数组中的最大值和最小值的差

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html" />
        <meta name="keywords" content="获取数组中的最大差值" />
        <meta name="description" content="获取数组中的最大值" />
        <meta name="author" content="KG" />
        <meta charset="utf-8">
        <title>获取数组中的最大值</title>
    </head>
    <body>
        <script>
            var arr=[500,21,6589,100000,1565,4897,546,65];
            
            var minProfit=arr[0],
            maxProfit=0;
            
            
            function getMaxProfit(arr){
                var targetVal =null;
                for(var i=0;i<arr.length;i++){
                    var currentVal=arr[i];
                    // 找出数组中最小的值
                    minProfit=Math.min(minProfit,currentVal);
                    // 找出数组中最大的值
                    maxProfit=Math.max(maxProfit,currentVal);
                    //求出数组中最大元素和最小元素的差值
                    targetVal=maxProfit-minProfit;
                }
                return targetVal;
            }
            console.log(getMaxProfit(arr));
        </script>
    </body>
</html>

关键方法:Math.min(num1,num2);找出两数中的最小值;

Math.max(num1,num2);找出两个数中的最大值;

posted @ 2020-04-20 10:06  KG-work-space  阅读(396)  评论(0编辑  收藏  举报