
显示成绩
<style>
* {
padding: 0;
margin: 0;
}
h1 {
text-align: center;
height: 50px;
line-height: 50px;
}
table {
width: 600px;
border: 1px solid #ccc;
text-align: center;
margin: auto;
border-spacing: 0px;
border-collapse: collapse;
}
table th,
table td {
border: 1px solid #ccc;
height: 30px;
}
</style>
<body>
<h1>成绩单</h1>
<table>
<thead>
<tr>
<th>学号</th>
<th>语文</th>
<th>数学</th>
<th>英语</th>
<th>总成绩</th>
<th>备注</th>
</tr>
</thead>
<tbody id="box">
</tbody>
</table>
<script>
var stu = [
{
xuehao: 1,
chinese: 105,
math: 62,
english: 118,
},
{
xuehao: 2,
chinese: 89,
math: 78,
english: 120,
},
{
xuehao: 3,
chinese: 86,
math: 74,
english: 80,
},
{
xuehao: 4,
chinese: 78,
math: 99,
english: 91,
},
{
xuehao: 5,
chinese: 107.5,
math: 98,
english: 70,
},
{
xuehao: 6,
chinese: 112,
math: 61,
english: 92,
},
{
xuehao: 7,
chinese: 101,
math: 79,
english: 104,
},
{
xuehao: 8,
chinese: 71,
math: 72,
english: 105,
},
{
xuehao: 9,
chinese: 56,
math: 68,
english: 61,
},
{
xuehao: 10,
chinese: 98,
math: 83,
english: 77,
},
];
//【1】先计算总成绩
//【2】单科成绩最高的需要有排序
//【3】按照总成绩最高的进行排序
//【4】结构渲染
//计算总成绩
var box=document.getElementById('box');
stu=stu.map(functiom(item){
item.total=item.chinese+item.math+item.english;
return item;
})
//单科目最高成绩需要有备注
var chineseMax=stu.sort(function(a,b){
return b.chinese-a.chinese})[0];
chineseMax.tip='语文成绩最高';
var mathMax = stu.sort(function (a, b) {
return b.math - a.math;
})[0];
mathMax.tip = "数学成绩最高";
var englishMax = stu.sort(function (a, b) {
return b.english - a.english;
})[0];
englishMax.tip = "英语成绩最高";
stu.sort(function(a,b){
return b.total-a.total;
})
box.innerHTML=render(stu);
function render(data){
var str='';
data.forEach(function(item,index){
str+=`<tr>
<td>${item.xuehao}</td>
<td>${item.chinese}</td>
<td>${item.math}</td>
<td>${item.english}</td>
<td>${item.total}</td>
<td>${item.tip ? item.tip : ""}</td>
</tr>`});
return str;
}
</body>
reduce 去重
<script>
var arr = [1, 1, 2, 2, 12, 34, 3, 3, 4, 5, 6, 4, 3, 5];
var str=arr.reduce(function(pre,item){
if(pre.indexOf(item)==-1){
return pre.concat(item);
}
return pre;
},[]);
console.log(str);
</script>
计算两个数组的交集
<script>
var nums1 = [1, 2, 2, 3, 5],nums2 = [2, 3, 4, 5, 6];
var res=nums1.filter(function(item){
return nums2.indexOf(item)!=-1;
}).reduce(function(pre.item){
if(pre.indexOf(item)==-1){
return pre.concat(item);
}
return pre;
})[];
consloe.log(res)
</script>
找出数组中消失的数据
<script>
var arr = [4, 3, 2, 7, 8, 2, 3, 1];
var newArr=[];
var max=arr.sort(function(a,b){
return b-a;
})[0];
var min=arr[arr.length-1];
for(var i=min;i<max;i++){
if(arr.indexOf(i)==-1){
newArr.push(i);
}
}
console.log(newArr);
</script>
找出数组中数据出现的次数
<script>
var arr = [1, 2, 3, 1, 1, 1, 2, 2, 3, 3, 4];
var obj={};
arr.forEach(function(item){
if(obj[item]){
obj[item]= ++obj[item];
}
else{
obj[item]==1;
}
});
for(var key in obj){
console.log(key + "出现的次数为" + obj[key]);
}
</script>