练习作业3.html 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <ul id="box"></ul>
  10. <script>
  11. /*
  12. 题目:使用 HTML 和 JavaScript 使用 for of 方法计算出学生所有成绩的总和,并将结果显示在页面上。
  13. 要求:
  14. 使用js在 HTML 中创建<li> 元素,用于显示结果。
  15. 要求页面显示样式为:学生姓名:张三,总成绩:xxx分。
  16. 使用 JavaScript 的 for of、for in 方法进行操作。
  17. 可用 css/js 为列表项添加样式,如设置字体大小、颜色等。
  18. */
  19. const arr = [
  20. {
  21. name: '张三',
  22. score: {
  23. chinese: 85,
  24. math: 80,
  25. english: 77
  26. }
  27. },{
  28. name: '李四',
  29. score: {
  30. chinese: 66,
  31. math: 72,
  32. english: 55
  33. }
  34. },{
  35. name: '王五',
  36. score: {
  37. chinese: 87,
  38. math: 99,
  39. english: 100
  40. }
  41. },{
  42. name: '赵六',
  43. score: {
  44. chinese: 40,
  45. math: 62,
  46. english: 53
  47. }
  48. },{
  49. name: '田七',
  50. score: {
  51. chinese: 88,
  52. math: 92,
  53. english: 77
  54. }
  55. }
  56. ]
  57. // 创建函数对分数进行汇总 接受分数对象并进行加和处理
  58. function scoreSum(score){
  59. let sum = 0;
  60. // 使用for in 循环遍历对象 key 是每次对象的属性值
  61. for(let key in score){
  62. sum += score[key];
  63. }
  64. return sum;
  65. }
  66. // 创建新数组存储学生姓名和总分
  67. let resArr = arr.map(function(item){
  68. return {
  69. name : item.name,
  70. sum : scoreSum(item.score)
  71. }
  72. })
  73. // 使用for of 循环遍历数组
  74. let oBox = document.getElementById('box');
  75. for(let item of resArr){
  76. let oLi = document.createElement('li');
  77. oLi.innerText = `学生姓名:${item.name}, 总成绩:${item.sum}分`;
  78. oBox.appendChild(oLi);
  79. }
  80. </script>
  81. </body>
  82. </html>