二维数组求平均值,最大值,最小值demo
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-cn"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <title>网页标题</title> <meta name="keywords" content="关键字列表" /> <meta name="description" content="网页描述" /> <link rel="stylesheet" type="text/css" href="" /> <style type="text/css"></style> <script type="text/javascript"> //求数组平均值,最大值,最小值 var arr=[ [32,15,23,13], [23,33,23,12], [13,23,24,9] ]
//总和值,初始化0 var sum=0;
//总行数值,初始化0 var n=0;
//初始化最大值 var max=arr[0][0];
//初始化最小值 var min=arr[0][0];
for(var i=0;i<arr.length;i++){ for(var j=0;j<arr[i].length;j++){ sum+=arr[i][j]; n++; if(max<arr[i][j]){//比较最大值 比现有最大值小说明是最大值 //示例:32<33 判断语句真,赋值33是max max=arr[i][j]; } if(min>arr[i][j]){//比较最小值 比现有最小值大说明是最小值 //示例:32>12 判断语句真,赋值12是min min=arr[i][j]; } } }document.write("平均值:"+sum/n+"最大值:"+max+"最小值:"+min); </script> </head> <body> </body> </html>
三目运算获取最大值demo
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-cn"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <title>网页标题</title> <meta name="keywords" content="关键字列表" /> <meta name="description" content="网页描述" /> <link rel="stylesheet" type="text/css" href="" /> <style type="text/css"></style> <script type="text/javascript"> function genMax(a,b){ var max=a>b?a:b; document.write(max+"最大<br/>"); } genMax(50,37); genMax(50,98); genMax(42,87); </script> </head> <body> </body> </html>