12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <ul id="box"></ul>
- <script>
- /*
- 题目:使用 HTML 和 JavaScript 使用 for of 方法计算出学生所有成绩的总和,并将结果显示在页面上。
- 要求:
- 使用js在 HTML 中创建<li> 元素,用于显示结果。
- 要求页面显示样式为:学生姓名:张三,总成绩:xxx分。
- 使用 JavaScript 的 for of、for in 方法进行操作。
- 可用 css/js 为列表项添加样式,如设置字体大小、颜色等。
- */
- const arr = [
- {
- name: '张三',
- score: {
- chinese: 85,
- math: 80,
- english: 77
- }
- },{
- name: '李四',
- score: {
- chinese: 66,
- math: 72,
- english: 55
- }
- },{
- name: '王五',
- score: {
- chinese: 87,
- math: 99,
- english: 100
- }
- },{
- name: '赵六',
- score: {
- chinese: 40,
- math: 62,
- english: 53
- }
- },{
- name: '田七',
- score: {
- chinese: 88,
- math: 92,
- english: 77
- }
- }
- ]
- // 创建函数对分数进行汇总 接受分数对象并进行加和处理
- function scoreSum(score){
- let sum = 0;
- // 使用for in 循环遍历对象 key 是每次对象的属性值
- for(let key in score){
- sum += score[key];
- }
- return sum;
- }
- // 创建新数组存储学生姓名和总分
- let resArr = arr.map(function(item){
- return {
- name : item.name,
- sum : scoreSum(item.score)
- }
- })
- // 使用for of 循环遍历数组
- let oBox = document.getElementById('box');
- for(let item of resArr){
- let oLi = document.createElement('li');
- oLi.innerText = `学生姓名:${item.name}, 总成绩:${item.sum}分`;
- oBox.appendChild(oLi);
- }
- </script>
- </body>
- </html>
|