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

2023-06-26,,

<!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);找出两个数中的最大值;

求一个number数组中的最大值和最小值的差的相关教程结束。

《求一个number数组中的最大值和最小值的差.doc》

下载本文的Word格式文档,以方便收藏与打印。