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>

猜你喜欢

转载自blog.csdn.net/double_sweet1/article/details/80328562