1. [代码] [JavaScript]代码 !DOCTYPE htmlhtmlheadmeta charset="UTF-8"titleDocument/title/headbodyscript type="text/javascript"//第一班的学生信息var classes1=[{name:'smith',age:19,gender:1},{name:'tom',age:20,gender:1},{name:'rose
1. [代码][JavaScript]代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script type="text/javascript"> //第一班的学生信息 var classes1=[ { name:'smith', age:19, gender:1 }, { name:'tom', age:20, gender:1 }, { name:'rose', age:19, gender:0 } ]; var classes2=[ { name:'jack', age:21 gender:1 }, { name:'tom', age:20, gender:0 }, { name:'rose', age:19, gender:0 } ]; //定义一个函数来求平均年龄 function getAverageAge(arr){ //求平均年龄 var avgAge=0; var length=arr.length;//这个班有多少人 var sum=0; for(var i=0;i<length;i++){ var stu=arr[i]; //从数组中取出的每一个元素是对象 sum=sum+stu.age;//从每一个对象中取出年龄 } avgAge=sum/length; return avgAge; } //定义一个函数求出每个班的男女比例 function getRatio(arr){ var female=0,male=0; var length=arr.length; var r; for(var i=0;i<length;i++){ var a=arr[i]; if(a.gender==1){ male++; }else{ female++; } r=male/female; return r; } } alert("一班的平均年龄:"+getAverageAge(classes1)); alert("二班的平均年龄:"+getAverageAge(classes2)); alert("一班的男女比例:"+getAverageAge(classes1)); alert("二班的男女比例:"+getAverageAge(classes2)); </script> </body> </html>