JavaScript(js)构造器的应用(求数组中平均数及大于平均数的人数)

来源:互联网 发布:win10 优化工具 编辑:程序博客网 时间:2024/04/30 12:51

JavaScript(js)构造器的应用(求数组中平均数及大于平均数的人数)

<!DOCTYPE html><html lang="en">    <head>        <meta charset="UTF-8">        <title>Title</title>    </head>    <body>    <script>        //构造器        function CreatePerson (name, age, score) {            this .name = name;            this .age = age;            this .score = score;        }        //创建对象4个        var stu1 = new CreatePerson ('ZhangSan', 23, 87);        var stu2 = new CreatePerson ('LiSi', 23, 8);        var stu3 = new CreatePerson ('WangEr', 25,90);        var stu4 = new CreatePerson ('MaZi',23 ,60);        //stu1,stu10是同一个,对象是引用类型,变量是赋值类型,所以打印的score是97        var stu10 = stu1;        stu10.score = 97;        document.write ("score:" + stu1.score + "<br>");         //求数组中大于平均分的学生的人数        var stus = [stu1, stu2, stu3, stu4];        var sum = 0;        var avg = 0, count=0;         for(var i in stus) {           sum += stus[i].score;        }        avg = sum / stus.length;        for (var i in stus) {            if (stus[i].score > avg) {                count ++;            }        }        document.write ('avg:' + avg  + "<br>");        document.write ('count:' + count);     </script>     </body></html>

浏览器页面打印是:
       score:97
       avg:63.75
       count:2

0 0