1. 程式人生 > >javascript中max,min的用法

javascript中max,min的用法

在js中,求一個數組中最大值或最小值常用的方法是:Math.max.apply(function,arr);這裡的arr是具體我們將要求的 陣列的 陣列名。function為要呼叫的方法,當function為null時,預設為上文。

同理同min.

之所以專門把max在js中的用法提出來講是因為在js中,直接使用Math.max()求一個數組的最大值是行不通的,親測有效地是上述方法。

例題如下:輸入10本書的價格,求其最大值,最小值和平均值。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
	<title>實驗二-四</title>
</head>
<body>
     <table>
         <script type="text/javascript">
            var n = new Array();
            var maxPrice = 0;
            var minPrice = 0;
            var avePrice = 0;
            var sum = 0;
            for(i=1; i<=10; i++){
            	document.writeln("<tr><td>請輸入第"+i+"本書的價格:</td><td><input type=text name=book></td></tr>");
            }
            function calculate(){
	            for(i=0; i<10; i++){
	            	n[i] = Number(document.getElementsByName("book")[i].value);
	            	sum+=n[i];
	            }
	            maxPrice = Math.max.apply(null,n);
	            minPrice = Math.min.apply(null,n);
	            avePrice = (sum/10);
	            document.emmm.maxPrice.value = maxPrice;
	            document.emmm.minPrice.value = minPrice;
	            document.emmm.avePrice.value = avePrice;
            }
        </script>
     </table>
     <input type="button" onclick="calculate()" value="提交" >
     <form name="emmm">
         最高價格為:<input type="text" name="maxPrice"><br>
         最低價格為:<input type="text" name="minPrice"><br>
         平均價格為:<input type="text" name="avePrice">
     </form>
              
</body>
</html>