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>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Coding101

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值