Object.defineProperties 练习

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <title>Document</title>
 8 </head>
 9 
10 <body>
11     <script>
12         
13         //需求,为stus添加一个属性,获取score分数的总和
14         var stus = {
15             scores: [
16                 { name: "张三", score: 65 },
17                 { name: "李四", score: 86 },
18                 { name: "王五", score: 39 },
19                 { name: "赵六", score: 89 },
20             ]
21         };
22 
23         //为 stus 添加一个属性 total 获取总数
24         Object.defineProperties(stus, {
25             total: {
26                 get: function(){
27                     //声明一个变量
28                     let t = 0;
29                     for(let i = 0;i<this.scores.length;i++){
30                         t += this.scores[i].score;//5
31                     }
32                     return t;
33                 },
34                 enumerable: true  //可遍历
35             }
36         });
37 
38         // console.log(stus);
39         // for(let i in stus){
40         //     console.log(i);
41         // }
42 
43         //得到总数
44         console.log(stus.total);
45 
46     </script>
47 </body>
48 
49 </html>

 

posted @ 2020-06-06 19:23  全情海洋  阅读(163)  评论(0编辑  收藏  举报